What is the HashSet.clear() method in Java?
The HashSet.clear() method is present in the HashSet class inside the java.util package.
It clears all the elements from the HashSet, i.e., it empties the existing HashSet but does not delete the HashSet.
Let’s understand this with the help of an example. Suppose that a HashSet contains [1, 8, 5, 3 , 0]. Upon using the hashSet.clear() method, the HashSet becomes empty and when we display the elements of the HashSet, we get an empty array ([ ]).
Parameter
The HashSet.clear() doesn’t accept any parameters.
Return value
The HashSet.clear() doesn’t return any value.
Code
Let’s have a look at the code:
import java.io.*;import java.util.HashSet;class Main{public static void main(String args[]){HashSet<Integer> hash_set1 = new HashSet<Integer>();hash_set1.add(1);hash_set1.add(8);hash_set1.add(5);hash_set1.add(3);hash_set1.add(17);hash_set1.clear();System.out.println("hash_set1 after using HashSet.clear(): "+ hash_set1);}}
Explanation
-
In lines 1 and 2, we import the required packages and classes.
-
In line 4, we make the
Mainclass. -
In line 6, we make the
main()function. -
In line 8, we declare a
HashSetof the integer type i.e.,hash_set1. -
From lines 9 to 13, we add the elements into the HashSet by using the
HashSet.add()method. -
In line 14, we use the
HashSet.clear()method to empty the Hashset. -
In line 16, we display the HashSet after using the
HashSet.clear()method with a message.