Reputation: 75545
Based on the Javadoc, the following code should print 6
. However, it outputs 3
for no apparent reason.
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());
}
}
Can anyone explain a) why I am seeing this behavior and b) How I can modify the code to fix it so that the extracted Bitset is of length 6 instead of 3?
Upvotes: 1
Views: 165
Reputation: 49362
Javadoc for BitSet#length(),says Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.
In your case the foo.get(15,21)
gives a BitSet
: [0, 0, 1, 0, 0, 0, 0]
. Hence the result is 2+1=3
.
Upvotes: 0
Reputation: 34900
Why it should return 6
? Let's see:
foo.get(15,21)
returns word equals 4
. In binary representation it is just 100
.
Let's read javadoc
of length()
method of BitSet
class:
Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.
Ok, we can now check it for 100
: the highest set bit is 2
(counting from 0
), plus one it will be 3
. Everything is correct.
Upvotes: 0
Reputation: 382092
From the javadoc :
Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.
The length only counts the set bits.
The bits are [0, 0, 1, 0, 0, 0, 0]
, that is false after the third one, hence the returned length.
You have nothing to do : your bitSet is fine, as would have been clear if you had used the size method.
Upvotes: 2