Java HashSet - size() Method
The java.util.HashSet.size() method returns the total number of elements present in the set.
Syntax
public int size()
Parameters
No parameter is required.
Return Value
Returns the total number of elements in the set.
Exception
NA
Example:
In the example below, the java.util.HashSet.size() method is used to find out the total number of elements in the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating hash set HashSet<Integer> MySet = new HashSet<Integer>(); //populating hash set MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); System.out.println("Size of MySet: "+ MySet.size()); //adding one more element in the HashSet MySet.add(50); System.out.println("Size of MySet: "+ MySet.size()); } }
The output of the above code will be:
Size of MySet: 4 Size of MySet: 5
❮ Java.util - HashSet