Java BitSet - cardinality() Method
The java.util.BitSet.cardinality() method returns the number of bits set to true in the given BitSet.
Syntax
public int cardinality()
Parameters
No parameter is required.
Return Value
Returns the number of bits set to true in the given BitSet.
Exception
NA
Example:
In the example below, the java.util.BitSet.cardinality() method is used to find the number of bits set to true in the given BitSet.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a BitSet BitSet BSet = new BitSet(); //populating the BitSet BSet.set(10); BSet.set(20); BSet.set(30); BSet.set(40); BSet.set(50); //printing the BitSet System.out.println("BSet contains: " + BSet); //printing cardinality of the BitSet System.out.println("BSet cardinality: " + BSet.cardinality()); } }
The output of the above code will be:
BSet contains: {10, 20, 30, 40, 50} BSet cardinality: 5
❮ Java.util - BitSet