The BitSet class 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. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

Constructors :
BitSet class has two constructors:

Constructor

Description

BitSet()

Creates a default object

BitSet( int size )

Allows us to specify the initial size i.e. the no. of bits that the BitSet can hold

NOTE:
By default, all bits are initialized to zero.

Some Important Methods :

Method

Description

Object clone()

Creates a copy of the invoking BitSet object.

void set( int index )

Sets the bit specified by index.

void set( int index, boolean v )

Sets the bit specified by index to the value passed in v. true sets the bit and false clears the bit

void or( BitSet bitSet )

ORs the contents of the invoking BitSet object with that specified by bitSet and places the result into the invoking object.

void and( BitSet bitSet )

ANDs the contents of the invoking BitSet object with that specified by bitSet and places the result into the invoking object

void andNot( BitSet bitSet )

For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared

void xor( BitSet bitSet )

XORs the contents of the invoking BitSet object with that specified by bitSet and places the result into the invoking object

void set( int startIndex, int endIndex )

Sets the bits from startIndex to (endIndex – 1)

void set( int startIndex, int endIndex, boolean v )

Sets the bits from startIndex to (endIndex – 1) to the value passed in v. true sets the bits and false clears the bits

From the output of the above program, it is clear that when toString() converts a BitSet object to its string equivalent, each set bit is represented by its position i.e., with toString() call in the SOPstatements --- System.out.println( bitSetA )

Then with and() method call, corresponding bits in the invoking BitSet (bitSetA) and the passed BitSet (bitSetB) are ANDed and the result is placed into the invoking BitSet (i.e., bitSetA). The result follows from normal AND semantics. Same applies for or() and xor()method calls with respective semantics.

With bitSetA.andNot( bitSetB ) method call, since bits at positions {1, 2, 3, 4} are set in bitSetB, corresponding bits in bitSetA are cleared. So bitSetA will become {}.

THINGS TO TRY

Consider the above program. Create another BitSet object, say, D with some start and end indices as shown above. Then call and(), or(), andNot() etc. on BitSet object D.