I am a novice programmer and I recently came across a BitArray data structure

I'm a beginner programmer, and I recently stumbled upon a BitArray data structure while reading a single book (more precisely, Pearls Programming). I wanted to learn a little and work a bit on BitArray, as I did not know about this before. I made a simple implementation in C # (such simple things as creating a BitArray, setting values, etc.), but when I wanted to try it in Java, it complained that BitArray was unknown. So I searched the web and changed BitArray to BitSet. Is BitSet the equivalent of BitArray in Java? Also, I don’t quite understand the different values ​​of size () and length () in BitSet. Check out 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()); } } 

Exit:

 1000000010000001000000000000000000000000000000000000000000000000 64 16 

I thought I would get something like

 1000000010000001 16 16 

Where do these trailing zeros come from? Can someone explain this to me? thanks ~~

+6
source share
2 answers

The answer is pretty simple. The BitSet constructor simply says that it generates what is large enough for a given size, in fact it requires some internal size that works best.

And in your case it is 64 bit, see JavaDoc

+5
source

If you see the BitSet#size documentation, it says:

Returns the number of bits of space actually used by this BitSet, for represent bit values. The maximum element in the set is the size - the 1st element.

And for BitSet#length :

Returns the "logical size" of this BitSet: index of the highest set bit in BitSet plus one. Returns zero if the BitSet does not contain a set bit.

So you should use BitSet.length if you want to get the actual number of bits in your bitet. Because BitSet.size returns the memory used by your BitSet instance.

In addition, according to the documentation :

Note that the size is related to the implementation of the bit set, so it can be changed using the implementation

Thus, the size in your case is 64 bits, which can change automatically when you set a bit with an index greater than the specified length.

+5
source

All Articles