Last Updated : 11 Jul, 2025
The clear() method of the HashSet class in Java is used to clear all the elements from the HahSet. This method makes the HashSet empty but does not delete the HashSet itself. It simply removes all elements, leaving the set ready for reuse.
Syntax of HashSet clear() Methodvoid clear()
Key Points:
Example: This example demonstrates how the clear() method removes all the elements from the HashSet.
Java
// Java program to demonstrates the working of clear()
import java.util.*;
public class Geeks {
public static void main(String[] args)
{
// Create a HashSet
HashSet<Integer> hs = new HashSet<Integer>();
// Add elements to HashSet
hs.add(1);
hs.add(2);
hs.add(3);
System.out.println("HashSet before clear(): " + hs);
// Clear the HashSet
hs.clear();
System.out.println("HashSet After clear(): " + hs);
System.out.println("HashSet isEmpty(): "
+ hs.isEmpty());
}
}
HashSet before clear(): [1, 2, 3] HashSet After clear(): [] HashSet isEmpty(): true
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4