Working With BitSet Class in Java

Introduction

 
In this article, we are going to describe one of the important classes of the util package in Java. So we explain the use of the BitSet class test; also what is the need of the bit class. A 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.
 

BitSet Class

 
The BitSet class implements a vector of bits that can grow as needed. Each component of the bit set has a boolean value. 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.
 
Note: By default, all bits in the set initially have the value false. And something else to be concerned with is that when you pass a null parameter to any of the methods in a BitSet, that will result in a NullPointerException. A BitSet is not safe for multithreaded use without external synchronization.
 

BitSet Class Structure

  1. public class BitSet extends Object implements Cloneable, Serializable

BitSet Constructor Details

 
This class contains two constructors; one is a default constructor for creating default objects of a BitSet class and another is a constructor that takes as an int type one argument whose initial size is large enough to explicitly represent the bits with indices in the range 0 through nbits-1. All bits are initially false.
  1. public BitSet()  
  2.   
  3. public BitSet(int nbits)  

BitSet Methods Details

 
 BitSet Methods Details
 BitSet Methods Details
 
Example
  1. import java.util.BitSet;  
  2. class MyBitSetDemo {  
  3.     public static void main(String args[]) {  
  4.         BitSet bits1 = new BitSet(12);  
  5.         BitSet bits2 = new BitSet(24);  
  6.         // set some bits  
  7.         for (int i = 10; i < 32; i++) {  
  8.             if ((i % 2) == 0)  
  9.                 bits1.set(i);  
  10.             if ((i % 5) != 0)  
  11.                 bits2.set(i);  
  12.         }  
  13.         System.out.println("Initial  bits1: ");  
  14.         System.out.println(bits1);  
  15.         System.out.println("\\nInitial bits2: ");  
  16.         System.out.println(bits2);  
  17.         // AND bits  
  18.         bits2.and(bits1);  
  19.         System.out.println("\\nbits2 AND bits1: ");  
  20.         System.out.println(bits2);  
  21.         // OR bits  
  22.         bits2.or(bits1);  
  23.         System.out.println("\\nbits2 OR bits1: ");  
  24.         System.out.println(bits2);  
  25.         // XOR bits  
  26.         bits2.xor(bits1);  
  27.         System.out.println("\\nbits2 XOR bits1: ");  
  28.         System.out.println(bits2);  
  29.     }  
  30. }  
OUTPUT
 
BitSet Class