基于Javadoc ,以下代码应打印 6
。但是,它毫无明显原因地输出 3
。
import java.util.*;
public class BitSetStrangeness{
public static void main(String[] args){
BitSet foo = new BitSet();
int[] arbitrary = new int[] {
0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1
};
for (int i = 0; i < arbitrary.length; i++)
if (arbitrary[i] == 1) foo.set(i);
else foo.clear(i);
System.out.println(foo.get(15,21).length());
}
}
谁能解释一下 a) 为什么我会看到这种行为以及 b) 如何修改代码来修复它,以便提取的 Bitset 的长度为 6 而不是 3?
最佳答案
来自the javadoc :
Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.
长度只计算设置的位。
这些位是[0, 0, 1, 0, 0, 0, 0]
,第三个位之后为假,因此返回长度。
您无事可做:您的位集很好,如果您使用 size 就很清楚了方法。
关于Java BitSet 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16393067/