The BitSet ClassTo shift gears further, java.util includes the BitSet class as a convenient way to maintain and manipulate a set of bits. A BitSet instance can grow as needed, so you can create an empty set with the no-argument constructor as a starting point: public BitSet() If, on the other hand, you have an idea of how many bits you will need, you should create the BitSet with a specific initial size instead: public BitSet(int numberOfBits) Each bit in a BitSet is represented by a boolean value that can be examined, set, or cleared. Using an index value, you can set an individual bit to either true or false with the set or clear method, respectively: public void set(int whichBit) public void clear(int whichBit) A BitSet automatically grows to accommodate its highest set bit. For example, if you create a bit set of 20 bits and then call the set method on bit 45, the bit set automatically grows to contain at least 46 bits. Other than the bit at index 45, the new bits are all cleared initially. The size method tells you how many bits are in the current bit set, and length reports the highest set index plus one: public int size() public int length() You can test to see whether a bit is set or cleared using the get method, which returns a boolean result: public boolean get(int whichBit) BitSet also defines four methods that operate jointly on two bit sets. These operations manipulate the current bit set using bits from a second bit set. Corresponding bits are matched to perform the operation. In other words, bit 0 in the current bit set is compared to bit 0 in the second bit set. The bitwise operations are
The signatures of these bitwise operations are public void or(Bitset bits) public void and(Bitset bits) public void andNot(Bitset bits) public void xor(Bitset bits) |