Home » Java programming language

Java BitSet cardinality() Method with Example

BitSet Class cardinality() method: Here, we are going to learn about the cardinality() method of BitSet Class with its syntax and example.
Submitted by Preeti Jain, on January 21, 2020

BitSet Class cardinality() method

  • cardinality() method is available in java.util package.
  • cardinality() method is used to return the cardinality (i.e. the number of bits is set to true by using set() method ) in this Bitset.
  • cardinality() method is a non-static method, so it is accessible with the class object and if we try to access the method with the class name then we will get an error.
  • cardinality() method does not throw an exception at the time of returning cardinality of this Bitset.

Syntax:

    public int cardinality();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is int, it returns the cardinality of this Bitset.

Example:

// Java program to demonstrate the example 
// of int cardinality() method of BitSet.

import java.util.*;

public class CardinalityOfBitSet {
    public static void main(String[] args) {
        // create an object of BitSet
        BitSet bs = new BitSet(10);

        // By using set() method is to set
        // the values in BitSet 
        bs.set(10);
        bs.set(20);
        bs.set(30);
        bs.set(40);
        bs.set(50);

        // Display Bitset
        System.out.println("bs :" + bs);

        // By using cardinality() method is to return
        // the number of bits in this BitSet
        int cardinality = bs.cardinality();

        // Display BitSet 2
        System.out.println("bs.cardinality()  : " + cardinality);
    }
}

Output

bs :{10, 20, 30, 40, 50}
bs.cardinality()  : 5


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.