BitSet is a class defined in the java.util package. It creates an array of bits represented by 0s and 1s.
Syntax
public int cardinality()
Explanation:
The method returns the number of 1s in this BitSet.
Examples:
Input : set1 : {1, 2, 4} set2 : {} Output : 3 0
Java
// Java program illustrating Bitset Class functions. import java.util.*; public class GFG { public static void main(String[] args) { // Constructors of BitSet class BitSet bs1 = new BitSet(); BitSet bs2 = new BitSet(); BitSet bs3 = new BitSet(); /* set is BitSet class method explained in next articles */ bs1.set( 0 ); bs1.set( 1 ); bs1.set( 2 ); bs1.set( 4 ); // assign values to bs2 bs2.set( 4 ); bs2.set( 6 ); bs2.set( 5 ); bs2.set( 1 ); bs2.set( 2 ); bs2.set( 3 ); // Printing the 2 Bitsets System.out.println( "bs1 : " + bs1); System.out.println( "bs2 : " + bs2); System.out.println( "bs3 : " + bs3); // Performing logical AND // on bs2 set with bs1 System.out.println(bs1.cardinality()); System.out.println(bs2.cardinality()); System.out.println(bs3.cardinality()); } } |
bs1 : {0, 1, 2, 4} bs2 : {1, 2, 3, 4, 5, 6} bs3 : {} 4 6 0
Related Articles :