This example shows how to get HashSet size (HashSet length) in Java using the size method. This example also shows how to check if HashSet is empty using it.
How to get HashSet size in Java using the size method?
The size
method of the HashSet class returns the number of elements stored in the HashSet object.
1 |
public int size() |
The size
method returns an int containing the number of elements contained in the HashSet object. It returns 0 if there are no elements in the set object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.HashSet; public class JavaHashSetSizeExample { public static void main(String[] args) { /* * Create new and empty HashSet object */ HashSet<Integer> hsetNumbers = new HashSet(); /* * To get the HashSet size (or HashSet length), use * the size method */ int size = hsetNumbers.size(); //this will print 0 as there are no elements in the HashSet System.out.println("Size is: " + size); //add an element hsetNumbers.add(1); //this will print 1 as there is one element in the HashSet size = hsetNumbers.size(); System.out.println("Size is: " + size); } } |
Output
1 2 |
Size is: 0 Size is: 1 |
How to check if the HashSet object is empty?
We can get the size of the HashSet object and then compare it with 0 to check if the HashSet is empty as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* * Create new and empty HashSet object */ HashSet<Integer> hsetNumbers = new HashSet<Integer>(); /* * Get the size of the HashSet and then compare it * with the 0 to check if it is empty */ System.out.println( "Is empty? " + (hsetNumbers.size() == 0) ); //add some elements hsetNumbers.add(1); hsetNumbers.add(2); hsetNumbers.add(3); System.out.println( "Is empty? " + (hsetNumbers.size() == 0) ); |
Output
1 2 |
Is empty? true Is empty? false |
This example is a part of the Java HashSet Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 HashSet