I don't quite understand the different meanings of size()
and length()
in BitSet
. Check the code below:
public class Sandbox {
public static void main(String argv[])
{
BitSet bitSet1 = new BitSet(16);
bitSet1.set(0);
bitSet1.set(8);
bitSet1.set(15);
displayBitSet(bitSet1);
}
static void displayBitSet(BitSet bitSet)
{
for(int i=0;i<bitSet.size();i++)
{
boolean bit = bitSet.get(i);
System.out.print(bit?1:0);
}
System.out.println(" "+bitSet.size()+" "+bitSet.length());
}
}
Output is:
1000000010000001000000000000000000000000000000000000000000000000 64 16
I thought I would get something like
1000000010000001 16 16
Where do these trailing zeroes come from? Can someone explain this to me? thanks~~
answer is quite simple the BitSet
constructor just says it generates something which is big enough to the given size, actually it takes some internal size which is best matching.
And in your case this is 64 bit, see JavaDoc
If you see the documentation of BitSet#size
, it says:
Returns the number of bits of space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element.
And for BitSet#length
:
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.
So, you should use BitSet.length
, if you want to get the actual number of bits
in your bitset. Because, BitSet.size
returns the memory occupied by your BitSet
instance.
Also, according to the documentation:
Note that the size is related to the implementation of a bit set, so it may change with implementation
So the size in your case is 64 bit, which can change automatically, when you set bit at index greater than specified length.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With