The BitSet Class

   

The BitSet Class

To 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 or operation sets the bit in the current bit set if either the current bit or the second bit is set. If neither bit is set, the current bit remains cleared.

  • The and operation sets the bit in the current bit set only if the current bit and the second bit are set. Otherwise, the current bit is cleared.

  • The and not operation clears the bit in the current bit set if the second bit is set.

  • The xor operation sets the bit in the current bit set if only one of the two bits is set. If both are set, the current bit is cleared.

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) 
   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net