BitSet
ABitSetclass creates a special type of array that holds bit values. This array can increase in size
as needed. This makes it similar to a vector of bits. TheBitSetconstructors are shown here:
BitSet( )
BitSet(intsize)
The first version creates a default object. The second version allows you to specify its initial
size (that is, the number of bits that it can hold). All bits are initialized to zero.
BitSetdefines the methods listed in Table 18-2.
Chapter 18: java.util Part 2: More Utility Classes 505
Method Description
void and(BitSetbitSet) ANDs the contents of the invokingBitSetobject with those
specified bybitSet.The result is placed into the invoking
object.
void andNot(BitSetbitSet) For each 1 bit inbitSet,the corresponding bit in the invoking
BitSetis cleared.
int cardinality( ) Returns the number of set bits in the invoking object.
void clear( ) Zeros all bits.
void clear(intindex) Zeros the bit specified byindex.
void clear(intstartIndex,
intendIndex)
Zeros the bits fromstartIndextoendIndex–1.
Object clone( ) Duplicates the invokingBitSetobject.
boolean equals(ObjectbitSet) Returnstrueif the invoking bit set is equivalent to the one
passed inbitSet.Other wise, the method returnsfalse.
void flip(intindex) Reverses the bit specified byindex.
void flip(intstartIndex,
intendIndex)
Reverses the bits fromstartIndextoendIndex–1.
boolean get(intindex) Returns the current state of the bit at the specified index.
BitSet get(intstartIndex,
intendIndex)
Returns aBitSetthat consists of the bits fromstartIndex
toendIndex–1. The invoking object is not changed.
int hashCode( ) Returns the hash code for the invoking object.
boolean intersects(BitSetbitSet) Returnstrueif at least one pair of corresponding bits within
the invoking object andbitSetare 1.
boolean isEmpty( ) Returnstrueif all bits in the invoking object are zero.
int length( ) Returns the number of bits required to hold the contents of
the invokingBitSet. This value is determined by the location
of the last 1 bit.
int nextClearBit(intstartIndex) Returns the index of the next cleared bit (that is, the next
zero bit), starting from the index specified bystartIndex.
TABLE 18-2 The Methods Defined byBitSet