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: TheBitSetto intersect with.
Return value
boolean: This method returnstrueif there are set bits at common indices. Otherwise, it returnsfalse.
Code
import java.util.BitSet;public class Main{public static void main(String[] args) {// Create empty BitSet objectBitSet bitSet1 = new BitSet();// Set the bit at index 2bitSet1.set(2);// Set the bit at index 3bitSet1.set(3);// Create empty BitSet objectBitSet bitSet2 = new BitSet();// Set the bit at index 3bitSet2.set(3);// Set the bit at index 4bitSet2.set(4);// intersects operation on bitset1 and bitset2boolean commonSetBitsFound = bitSet1.intersects(bitSet2);// print the result of the operationSystem.out.printf("%s.intersects(%s) = %s", bitSet1, bitSet2, commonSetBitsFound);}}
Explanation
- Line 1: We import the
BitSetclass. - Line 7: We create the first
BitSetobject calledbitSet1. - Line 10: We set the bit at index
2of thebitSet1object. - Line 13: We set the bit at index
3of thebitSet1object. - Line 16: We create the second
BitSetobject calledbitSet2. - Line 19: We set the bit at index
3of thebitSet2object. - Line 22: We set the bit at index
4of thebitSet2object. - Line 25: We perform the
intersectsoperation onbitset1andbitset2that returns abooleanvalue. - Line 28: We print the result of the
intersectsoperation.