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:
NOTE:
By default, all bits are initialized to zero.
Some Important Methods :
BitSetDemo class BitSetDemo { public static void main(String arg[]) { BitSet bitSetA = new BitSet(); bitSetA.set(2); bitSetA.set(3); bitSetA.set(4); bitSetA.set(5); System.out.println("bitSetA = " + bitSetA); BitSet bitSetB = new BitSet(); bitSetB.set(1, 5); System.out.println("bitSetB = " + bitSetB); // Clone of bitSetA BitSet bitSetC = new BitSet(); bitSetC = (BitSet) bitSetA.clone(); System.out.println("bitSetC = " + bitSetC); // AND bits bitSetA.and(bitSetB); System.out.println("bitSetA and bitSetB = " + bitSetA); // OR bits bitSetA.or(bitSetB); System.out.println("bitSetA or bitSetB = " + bitSetA); // AND NOT bitSetA.andNot(bitSetB); System.out.println("bitSetA and not bitSetB = " + bitSetA); // XOR bits bitSetC.xor(bitSetB); System.out.println("bitSetC xor bitSetB = " + bitSetC); } } OUTPUTbitSetA = {2, 3, 4, 5} bitSetB = {1, 2, 3, 4} bitSetC = {2, 3, 4, 5} bitSetA and bitSetB = {2, 3, 4} bitSetA or bitSetB = {1, 2, 3, 4} bitSetA and not bitSetB = {} bitSetC xor bitSetB = {1, 5} DESCRIPTIONFrom 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.
|