The HashSet.clear() method in Java is used to remove all elements from a HashSet. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.
Table of Contents
- Introduction
clearMethod Syntax- Examples
- Clearing a HashSet
- Checking If a HashSet Is Empty After Clearing
- Conclusion
Introduction
The HashSet.clear() method is a member of the HashSet class in Java. It allows you to remove all elements from a HashSet, effectively making it empty. This method is useful when you want to reuse an existing HashSet without creating a new instance.
clear Method Syntax
The syntax for the clear method is as follows:
public void clear()
- The method does not take any parameters.
- The method does not return any value.
Examples
Clearing a HashSet
The clear method can be used to remove all elements from a HashSet.
Example
import java.util.HashSet;
public class ClearExample {
public static void main(String[] args) {
// Creating a HashSet of Strings
HashSet<String> languages = new HashSet<>();
// Adding elements to the HashSet
languages.add("Java");
languages.add("Python");
languages.add("C");
// Printing the HashSet before clearing
System.out.println("HashSet before clear: " + languages);
// Clearing the HashSet
languages.clear();
// Printing the HashSet after clearing
System.out.println("HashSet after clear: " + languages);
}
}
Output:
HashSet before clear: [Java, C, Python]
HashSet after clear: []
Checking If a HashSet Is Empty After Clearing
After clearing a HashSet, you can check if it is empty using the isEmpty method.
Example
import java.util.HashSet;
public class ClearAndCheckExample {
public static void main(String[] args) {
// Creating a HashSet of Strings
HashSet<String> languages = new HashSet<>();
// Adding elements to the HashSet
languages.add("Java");
languages.add("Python");
languages.add("C");
// Clearing the HashSet
languages.clear();
// Checking if the HashSet is empty
boolean isEmpty = languages.isEmpty();
// Printing the result
System.out.println("Is HashSet empty after clear? " + isEmpty);
}
}
Output:
Is HashSet empty after clear? true
Conclusion
The HashSet.clear() method in Java provides a way to remove all elements from a HashSet, making it empty. This can be useful for reusing a HashSet without creating a new instance. After calling the clear method, the HashSet will be empty, and you can verify this using the isEmpty method.