Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hashset
java
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}
Use hashset.size() function in Java

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.

RELATED TAGS

hashset
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring