Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the HashSet.isEmpty() 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.

The HashSet.isEmpty() method is present in the HashSet class inside the java.util package. It is used to check whether a HashSet contains any elements in it or not.

Let’s understand with the help of some examples:

  • Suppose a HashSet contains [1, 8, 5, 3, 0]. It contains some elements, i.e., the HashSet is not empty. So, the result of the HashSet.isEmpty() method is false.

  • Now, suppose a HashSet contains [ ]. It doesn’t contain any elements, i.e., the HashSet is empty. So, the result of the HashSet.isEmpty() method here is true.

Parameters

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

Return value

The HashSet.isEmpty() method returns a Boolean value where true denotes that the HashSet is empty and false denotes that the HashSet is not empty.

Code

Let’s have a look at the code:

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("HashSet is empty? : " +
hash_set.isEmpty());
hash_set.clear();
System.out.println("HashSet is empty? : " +
hash_set.isEmpty());
}
}
Using the hashset.isEmpty() function in Java

Explanation

  • In lines 1 and 2, we imported the required packages and classes.
  • In line 4, we defined the Main class.
  • In line 6, we created the main() function.
  • In line 8, we declared the HashSet as Integer type.
  • In lines 10 to 14, we add the elements into the HashSet by using the HashSet.add() method.
  • In line 15, we displayed the result, that is whether the HashSet is empty or not using the HashSet.isEmpty() method with a message.
  • In line 17, we removed all the elements from the HashSet by using the HashSet.clear() method.
  • In line 19, we displayed the result using the HashSet.isEmpty() method with a message.

RELATED TAGS

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