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.
Hashtable.clear()
method does not take any parameters.
This method does not return anything.
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 [ ]
.
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);}}
Main
class.main
function.Hashtable
consisting of Integer type keys and string type values.Hashtable
by using the Hashtable.put()
method.Hashtable
.Hashtable
using Hashtable.clear()
method.Hashtable
with a message.In this way, we can use the Hashtable.clear()
function to remove all the keys from the Hashtable
.