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

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

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

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.