1. Introduction
In Java, the HashSet class provides a method named isEmpty() that is used to check if the set is empty or not. It returns true if the set contains no elements and false otherwise. This method is helpful when you need to ensure that a HashSet has elements before performing operations on it.
2. Program Steps
1. Create a HashSet object and add some elements to it.
2. Use the isEmpty() method to check if the HashSet is empty.
3. Print the result.
4. Clear the HashSet using the clear() method.
5. Again, check if the HashSet is empty after clearing it and print the result.
3. Code Program
import java.util.HashSet;
public class HashSetIsEmpty {
public static void main(String[] args) {
// Step 1: Create a HashSet object and add some elements to it
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Use the isEmpty() method to check if the HashSet is empty
boolean isEmptyBeforeClear = fruits.isEmpty();
// Step 3: Print the result
System.out.println("Is the HashSet empty before clear?: " + isEmptyBeforeClear);
// Step 4: Clear the HashSet using the clear() method
fruits.clear();
// Step 5: Again, check if the HashSet is empty after clearing it and print the result
boolean isEmptyAfterClear = fruits.isEmpty();
System.out.println("Is the HashSet empty after clear?: " + isEmptyAfterClear);
}
}
Output:
Is the HashSet empty before clear?: false Is the HashSet empty after clear?: true
4. Step By Step Explanation
Step 1: A HashSet named fruits is created and three elements – "Apple", "Banana", and "Cherry" are added to it.
Step 2: The isEmpty() method is called on the fruits HashSet to check if it is empty, and the result is stored in the boolean variable isEmptyBeforeClear.
Step 3: The result isEmptyBeforeClear is printed to the console, which is false, as the HashSet contains three elements.
Step 4: The clear() method is invoked on the fruits HashSet to remove all elements from it.
Step 5: Again, the isEmpty() method is used to check if the HashSet is empty after clearing, and the result isEmptyAfterClear is printed, which is now true as all the elements are removed.