Menu
Topics Index
...
`

BitSetDemo - Java Example Program


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);    
    }
}
OUTPUT

bitSetA = {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}

DESCRIPTION

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.

© meritcampus 2019

All Rights Reserved.

Open In App