HashSet isEmpty() Method in Java
The isEmpty() method of HashSet checks if the HashSet is empty or not. If the HashSet is empty then it returns true otherwise returns false.
More formally, it returns true if the size of the HashSet is equal to zero. If the size is greater than zero then the isEmpty() method returns false.
Syntax
public boolean isEmpty()
Parameters
It does not accept any parameter.
Return Value
It returns true if the HashSet is empty otherwise returns false.
Program 1
import java.util.HashSet; // This program shows // how to use isEmpty() method // to check if the HashSet is empty or not public class HashSetIsEmptyExample { public static void main(String[] args) { // Create an instance of HashSet HashSetset = new HashSet(); // Add elements to it set.add(10); set.add(20); set.add(30); set.add(40); set.add(50); // Display hashSet elements System.out.println("Set Elements : " + set); // HashSet has values here // So, isEmpty() returns false System.out.println("Is Set Empty? : " + set.isEmpty()); // Clear the hashSet set.clear(); // HashSet is empty here // So, call to isEmpty() returns true System.out.println("Is Set Empty? : " + set.isEmpty()); } }
Output
Set Elements : [50, 20, 40, 10, 30] Is Set Empty? : false Is Set Empty? : true
Explanation
- Create an instance of HashSet
- Add elements 10, 20, 30, 40, 50 to it
- Check if the HashSet is empty using the isEmpty() method. As the HashSet has values in it. So, the call to isEmpty() method returns false.
- Clear the HashSet. At this point, there are no elements in the HashSet.
- Call to the isEmpty() method returns true now.
Program 2
import java.util.HashSet; // This program shows // how to use isEmpty() method // to check if the HashSet of String elements // is empty or not public class HashSetIsEmptyExample { public static void main(String[] args) { // Create an instance of HashSet HashSetset = new HashSet(); // Add elements to it set.add("Adam"); set.add("Chris"); set.add("Charles"); set.add("Robert"); // Display hashSet elements System.out.println("Set Elements : " + set); // HashSet has values here // So, isEmpty() returns false System.out.println("Is Set Empty? : " + set.isEmpty()); // Clear the hashSet set.clear(); // HashSet is empty here // So, call to isEmpty() returns true System.out.println("Is Set Empty? : " + set.isEmpty()); } }
Output
Set Elements : [Adam, Charles, Robert, Chris] Is Set Empty? : false Is Set Empty? : true
0 Comments