The Uses Of BitSet Class In Java

Introduction

A BitSet class creates a special type of array that holds the bit values. BitSet array can increase in size as required. This makes it same as to a vector of bits.

Constructors used

  •  BitSet()
  •  BitSet( int size)

The first constructor creates a default object. The second constructor allows the user to specify its initial size (the number of bits that it can hold). All the bits are initialized to zero. BitSet implements the cloneable interface.

Methods used

  • void and (BitSet bitset):  Adds the contents of the invoking BitSet object with those specified by bitSet. The result is placed into invoking object.
  • void andNot(BitSet bitSet): For each one bit in bitSet, the corresponding bit in the invoking BitSet is cleared.
  • boolean get(int bitIndex): This method returns the current state of the bit at the specified index.
  • int hashCode(): Returns the hash code for the invoking object.
  • String toString(): This method returns the string equivalent of the invoking BitSet object.
  • void xor(BitSet bitSet): XORs the contents of the invoking BitSet object with that specified by BitSet. The result is placed into invoking object.

Open a new file in the editor and type the following code:

import java.util.BitSet;
class BitSetDemo {
    public static void main(String args[]) {
        BitSet bits1 = new BitSet(16);
        BitSet bits2 = new BitSet(16);
        for (int i = 0; i < 16; i++) {
            if ((i) == 0) bits1.set(i);
            if ((i) != 0) bits2.set(i);
        }
        System.out.println("Initial Pattern in bits1: ");
        System.out.println(bits1);
        System.out.println("\n Initial Pattern in bits2: ");
        System.out.println(bits2);
        bits2.and(bits1);
        System.out.println("\n bits2 AND bits1:");
        System.out.println(bits2);
        bits2.or(bits1);
        System.out.println("\n bits2 or bits1");
        System.out.println(bits2);
    }
}
  • Save the file as BitSetDemo.java
  • Compile the file using Javac BitSetDemo.java
  • Run the file using java BitSetDemo

The output from this program as below. When toString converts a BitSet object to its string equivalent, each set bit is represented by bit position. Cleared bits are not displayed.

Summary

BitSet class creates a special type of array that holds bit values. This array can increase in size. This makes it similar in a vector of bits.