Search code examples
javaarraysbitset

Java BitSet size() behavior


I was planning on using BitSet to manipulate the bits in a byte[] since a library exists.

However, it seems after creating a BitSet from a byte[], the minimum size of BitSet is 64, otherwise it ends up zero. Is there a requirement that there must be 8 bytes? Also, a byte[] that is equivalent to zero will always show up with zero size. I assumed it would still output the size of the byte array?

ie.

BitSet bs1 = BitSet.valueOf(new byte[] {0, 0, 0, 0, 0, 0, 1});  // bs1.size() == 64
BitSet bs2 = BitSet.valueOf(new byte[] {0, 0, 0, 0, 0, 0, 0, 1}); // bs2.size() == 64
BitSet bs3 = BitSet.valueOf(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 1});  // bs3.size() == 128
BitSet bs4 = BitSet.valueOf(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0});  // bs4.size() == 0
System.out.print(bs1.size() + " " + bs2.size() + " " + bs3.size() + " " +  bs4.size()); 

I'll probably end up writing my own function but I'm curious as to why this happens.

Thanks!


Solution

  • Just read the javadoc:

    size(): Returns the number of bits of space actually in use by this BitSet to represent bit values.

    Thing is: the BitSet pre-allocates space; and that is what size() tells you about! It does not tell you how many bits exactly you "put" into it!

    In other words: the BitSet starts with 64 "empty" bits; and as soon as you "put in" a value that requires more than those 64; you go to 128 bits of "allocation". Also note that size() depends on your JDK's implementation of BitSet.

    You might want to look into length() resp. valueOf(); probably that will help you solving your problem.