What is the HashSet.size() function in Java?

In this shot, we will learn how to use the HashSet.size() method in Java.

What is Hashset.size()?

The Hashset.size() method is present in the HashSet class inside the java.util package.

It is used to obtain the number of elements in the HashSet or the size of the HashSet.

Example

Let’s understand with the help of an example. Suppose that a HashSet contains the elements [1, 8, 5, 3, 0].

The number of elements in the HashSet is five. So, the result of the HashSet.size() method is 5.

Parameters

The HashSet.size() method does not accept any parameters.

Return

The HashSet.size() returns the number of elements present or the size of the HashSet.

Code

Let’s have a look at the code.

import java.io.*;
import java.util.HashSet;
class Main
{
public static void main(String args[])
{
HashSet<Integer> hash_set = new HashSet<Integer>();
hash_set.add(1);
hash_set.add(8);
hash_set.add(5);
hash_set.add(3);
hash_set.add(0);
System.out.println("The size of HashSet is: " +
hash_set.size());
}
}

Explanation

  • In lines 1 and 2, we imported the required packages and classes.

  • In line 4, we created a Main class.

  • In line 6, we created a main() function.

  • In line 8, we declared a HashSet of integer type.

  • From lines 10 to 14, we added the elements into the HashSet by using the HashSet.add() method.

  • In line 17, we displayed the size of the HashSet using HashSet.size() function with a message.

This is how the HashSet.size() function is used to get the number of elements present in a HashSet.

Free Resources