What is the BitSet.intersects() method in Java?

intersects() is an instance method of the BitSet. It checks whether the BitSet object contains any set bits at the same indices as the specified BitSet object.

The BitSet class implements a vector of bits that expands automatically as additional bits are required.

The intersects() method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, check the following import statement:

import java.util.BitSet;

Syntax


public boolean intersects(BitSet set)

Parameter(s)

  • BitSet set: The BitSet to intersect with.

Return value

  • boolean: This method returns true if there are set bits at common indices. Otherwise, it returns false.

Code

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);
// intersects operation on bitset1 and bitset2
boolean commonSetBitsFound = bitSet1.intersects(bitSet2);
// print the result of the operation
System.out.printf("%s.intersects(%s) = %s", bitSet1, bitSet2, commonSetBitsFound);
}
}

Explanation

  • Line 1: We import the BitSet class.
  • Line 7: We create the first BitSet object called bitSet1.
  • Line 10: We set the bit at index 2 of the bitSet1 object.
  • Line 13: We set the bit at index 3 of the bitSet1 object.
  • Line 16: We create the second BitSet object called bitSet2.
  • Line 19: We set the bit at index 3 of the bitSet2 object.
  • Line 22: We set the bit at index 4 of the bitSet2 object.
  • Line 25: We perform the intersects operation on bitset1 and bitset2 that returns a boolean value.
  • Line 28: We print the result of the intersects operation.

Free Resources