BigSet class in Java

Object Oriented ProgrammingJava8Java Programming

The java.util.BitSet class implements a vector of bits that grows as needed. Following are the important points about BitSet −

  • A BitSet is not safe for multithreaded use without external synchronization.

  • All bits in the set initially have the value false.

  • Passing a null parameter to any of the methods in a BitSet will result in a NullPointerException.

Class declaration

Following is the declaration for java.util.BitSet class −

public class BitSet    
   extends Object    
   implements Cloneable, Serializable

Important Methods

Sr.No.
Method & Description
1
void and(BitSet set)
This method performs a logical AND of this target bit set with the argument bit set.
2
int cardinality()
This method returns the number of bits set to true in this BitSet.
3
void clear()
This method sets all of the bits in this BitSet to false.
4
void clear(int bitIndex)
This method sets the bit specified by the index to false.


Example

 Live Demo

import java.util.BitSet;

public class Tester {
   public static void main(String[] args) {

      // create 2 bitsets
      BitSet bitset1 = new BitSet(8);
      BitSet bitset2 = new BitSet(8);

      // assign values to bitset1
      bitset1.set(0);
      bitset1.set(1);
      bitset1.set(2);
      bitset1.set(3);
      bitset1.set(4);
      bitset1.set(5);

      // assign values to bitset2
      bitset2.set(2);
      bitset2.set(4);
      bitset2.set(6);
      bitset2.set(8);
      bitset2.set(10);

      // print the sets
      System.out.println("Bitset1:" + bitset1);
      System.out.println("Bitset2:" + bitset2);

      // are bitsets intersects
      System.out.println("Bitset1 intersects Bitset2: " + bitset1.intersects(bitset2));

      // perform and operation between two bitsets
      bitset1.and(bitset2);

      // print the new bitset1
      System.out.println("Bitset1 after and operation: " + bitset1);

      // perform clear operation on a bitset
      bitset1.clear();

      // print the new bitset1
      System.out.println("Bitset1 after clear operation: " + bitset1);

      //print the cardinality of bitset
      System.out.println("Bitset2 cardinality: " + bitset2.cardinality());
   }
}

Output

Bitset1:{0, 1, 2, 3, 4, 5}
Bitset2:{2, 4, 6, 8, 10}
Bitset1 intersects Bitset2: true
Bitset1 after and operation: {2, 4}
Bitset1 after clear operation: {}
Bitset2 cardinality: 5
raja
Published on 20-Jul-2018 11:46:14
Advertisements