What is the Hashtable.clear() function in Java?
In this shot, we discuss how to use the Hashtable.clear() method in Java.
The Hashtable.clear() method is present in the Hashtable class inside the java.util package. It is used to remove all the keys from the specified Hashtable.
Parameter
Hashtable.clear() method does not take any parameters.
Return
This method does not return anything.
Example
Let’s understand this with the help of an example.
Suppose we have a HashTable = {1 = Let's, 5 = see, 2 = Hashtable.clear(), 27 = method}
When we use HashTable.clear() method on this HashTable, it removes all keys from the HashTable, making the HashTable blank.
So, the result of the HashTable.clear() method is [ ].
Code
Let’s look at the code snippet below to understand this better.
import java.util.*;class Main{public static void main(String[] args){Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();h1.put(1, "Let's");h1.put(5, "see");h1.put(2, "Hashtable.clear()");h1.put(27, "method");h1.put(9, "in java.");System.out.println("The Hashtable is: " + h1);h1.clear();System.out.println("The Hashtable after using Hashtable.clear() method is: " + h1);}}
Explanation
- In line 1, we import the required package.
- In line 2, we make a
Mainclass. - In line 4, we make a
mainfunction. - In line 6, we declare a
Hashtableconsisting of Integer type keys and string type values. - In lines 9 to 13, we insert values in the
Hashtableby using theHashtable.put()method. - In line 16, we display the original
Hashtable. - In line 17, we remove all the keys from the
HashtableusingHashtable.clear()method. - In line 18, we display the
Hashtablewith a message.
In this way, we can use the Hashtable.clear() function to remove all the keys from the Hashtable.