In this example we will show how to remove all elements contained in Java HashSet or clear HashSet object with clear or removeAll methods. We may also see how to check if HashSet object is empty with isEmpty method. In addition, we may use the clear() method in the HashSet class to remove all elements.
Source Code
package com.beginner.examples;
import java.util.HashSet;
public class RemoveAllElementOfHashSet {
public static void main(String[] args) {
// Create a HashSet object
HashSet hSet = new HashSet();
// Add Elements
hSet.add("A");
hSet.add("B");
hSet.add("C");
// Remove all
hSet.clear();
System.out.println("All deleted:"+hSet);
}
}
Output:
All deleted:[]
References
Imported packages in Java documentation: