Search code examples
javabitset

How get real length of Bitset?


I read about size() and length() functions of BitSet class on JavaDoc and I understand the logic behind them.

But I need a function which returns the real size of a BitSet (the number of bits that I inserted into it). For example following code results in 0 and 64, but I need a function which return 5.

BitSet test = new BitSet(10);
for (int i = 0; i < 5; i++) {
    test.set(i, false);
}
System.out.println("len = " + test.length());
System.out.println("size = " + test.size());

Solution

  • BitSet has 3 methods that describes its state (in sense of length and set bits).

    1. length - Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.
    2. size - Returns the number of bits of space actually in use by this BitSet to represent bit values.
    3. cardinality - Returns the number of bits set to true in this BitSet.

    If you need to track number of set bits cardinality method is the answer. Notice that it tracks only true bits.

    If you need to track any call of set the simplest solution is to have another counter variable. So you can create a wrapper class or maybe extend BitSet (this can be not the best solution). Anyway, in this case you have to do it by hand.

    My guess is that you thought you can treat BitSet as List or something where you have capacity (size in BitSet case) and size - the actual number of elements in a list. But for a BitSet only true bits make sense.