1

I'm developing in Java (JDK 1.8) and manipulating BitSets. I came accross a strange issue.

I'm instantiating a BitSet of size 160 like:

BitSet example = new BitSet(160);

I want to check the size using the size() method that gives the number of bits in the bitset. In the documentation it is said that the constructor with an int N as parameter is creating a bitset of N bits.

But when I do check the size right after with

example.size()

I obtain the value

192

I do not understand why, does anyone came across this kind of problem ? link to documentation : http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html

1
  • 3
    From the doc: Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. Jul 4, 2015 at 18:53

2 Answers 2

5

This is because the BitSet constructor creates a BitSet "whose initial size is large enough to explicitly represent" bits in the range given by the parameter. So the actual size will be at least the number you give in the parameter, but not necessarily equal to that number.

The reason it uses 192 in particular is that 192 is a fairly nice binary number: 64 * 3.

4
  • Ok I see it now, thank you very much! So I guess there is no way to create a bitset that contains exactly the number of bits given in the constructor. I'll use a simple array.
    – thiout_p
    Jul 4, 2015 at 18:59
  • @thiout_p Why do you need a bitset with exactly a certain size? Have you determined that the memory constraints for the program you're building are really that strict?
    – Sam Estep
    Jul 4, 2015 at 19:06
  • @RedRobotHood It is just that I have to implement a model that is a chunk of bits and I wanted to stick to it as much as possible but I'll do otherwise. Thank you for pointing out the important word in the doc!
    – thiout_p
    Jul 4, 2015 at 19:14
  • @thiout_p The thing is, assuming you really are just dealing with a long string of bits as bits, using BitSet would be both fast and convenient. The only reason not to use it would be if the extra padding bits really take up too much RAM for your purposes, which I find unlikely.
    – Sam Estep
    Jul 4, 2015 at 19:17
0

Because the BitSet is actually used long[] to store 0/1 .

private void initWords(int nbits) {
    words = new long[wordIndex(nbits-1) + 1];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.