Hi All, I am using a BitSet to represent a set of boolean. I am unable to find a method that will give me the current number of booleans in the set. The size() provides the physical memory bits reserved for this set and can be larger then what was requested. For example when an object of BitSet is created with following constructor: BitSet bs = new BitSet(10); The size() reports 64. The length() reports 0 as no bit is set to true yet. I want a method that will report back 10. And if 15th bit is set to true, then it should report 15 as now client has attempted to store 15 booleans in this set. Anything avaialble? Thanks
Looking at the documentation [and source code] I would say you are out of luck. The "BitSet" instance will dynamically--and automatically-grow to accomodate what you do. I threw together the following code:
The first line prints out "128", the last line also prints out "128", and in between it prints out values for indexes 0-682. The initial constructor indicates that you want at least 20 slots, and you get 64 because it stores the bits on a "long", which is 64 bits in length. Thus the ".size()" will always return a multiple of 64. The "set(10)" and "set(40)" won't change the size (still 64), but the call to "set(100)" causes it to automatically allocate another long, giving you a size of 128. The ".get(i)" in the loop indicates that you can pass in any (non-zero) index and if it is past the current allocation, you get back "false". The fact that the length is still 128 after the loop shows that it didn't re-allocate space for the extra 555 bits processed in the loop. So it looks like you can't do what you want to do. As a possible work-around you could do the following: NOTE: This code was inserted AFTER Joe made his post, but before I saw it.
You create a new class where you track the maximum index used in a set/flip/... operation. This class only overrides the "set()" method, and you'd need to override any others that you wanted to use. The "getMaxIndex()" would let you know the actual range accessed. [ October 29, 2003: Message edited by: Wayne L Johnson ] [ October 29, 2003: Message edited by: Wayne L Johnson ]