What is BitSet.andNot() in Java?

Overview

andNot() is an instance method of the BitSet class that is used to clear all of the bits in the current BitSet object. The current BitSet object’s corresponding bit is set in the specified BitSet object.

Let’s say there are two BitSet objects. The bits at indexes 2 and 3 are set in the first object, and the bits at indexes 3 and 4 are set in the second object.

Invoking the method andNot() on the first object, while passing the second object, will modify the first object where the bit at index 2 is set, because the index 3 is the common set bit between the objects and it will be masked.

The andNot method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, use the following import statement.

import java.util.BitSet;

Syntax


public void andNot(BitSet set)

Parameters

  • BitSet set: The BitSet object with which to mask the current BitSet object.

Return value

This method does not return anything.

Code

import java.util.Arrays;
import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet1 = new BitSet();
// Set the bit at index 2
bitSet1.set(2);
// Set the bit at index 3
bitSet1.set(3);
// Create empty BitSet object
BitSet bitSet2 = new BitSet();
// Set the bit at index 3
bitSet2.set(3);
// Set the bit at index 4
bitSet2.set(4);
// andNot operation on bitset1
bitSet1.andNot(bitSet2);
// print the result of the operation
System.out.printf("%s.andNot(%s) = %s", bitSet1, bitSet2, bitSet1);
}
}

Free Resources