Java HashSet.clear() – Examples

In this tutorial, we will learn about the Java HashSet.clear() method, and learn how to use this method to remove all the elements from this HashSet, with the help of examples.

clear()

HashSet.clear() removes all of the elements from this HashSet.

Syntax

The syntax of clear() method is

</>
Copy
HashSet.clear()

Returns

The method returns void.

Example 1 – clear()

In this example, we will create and initialize a HashSet of Strings with some elements. We will then call clear() method on this HashSet. All the elements must be removed from this HashSet.

Java Program

</>
Copy
import java.util.Arrays;
import java.util.HashSet;

public class Example {  
	public static void main(String[] args) {  
		HashSet<String> hashSet = new HashSet<String>(Arrays.asList("a", "b", "c"));
		System.out.println("Original HashSet    : " + hashSet);
		
		hashSet.clear();
		System.out.println("HashSet after clear : " + hashSet);
    }  
}

Output

Original HashSet    : [a, b, c]
HashSet after clear : []

Example 2 – clear() – Empty HashSet

In this example, we will create an empty HashSet and try to clear this HashSet by calling clear() method. Since, the HashSet is already empty, the resulting HashSet and the original HashSet shall be empty as expected.

Java Program

</>
Copy
import java.util.HashSet;

public class Example {  
	public static void main(String[] args) {  
		HashSet<String> hashSet = new HashSet<String>();
		System.out.println("Original HashSet    : " + hashSet);
		
		hashSet.clear();
		System.out.println("HashSet after clear : " + hashSet);
    }  
}

Output

Original HashSet    : []
HashSet after clear : []

Example 3 – clear() – Null HashSet

In this example, we will initialize a HashSet with null. If we call clear() method on this null object, the method would throw java.lang.NullPointerException.

Java Program

</>
Copy
import java.util.HashSet;

public class Example {  
	public static void main(String[] args) {  
		HashSet<String> hashSet = null;
		hashSet.clear();
    }  
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:6)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashSet.clear() method, and also learnt how to use this method with the help of examples.