What is the Hashtable.clear method in Java?

A hash table is a collection of key-value pairs. The object to be used as a key should implement the hashCode and equals methods and the key and the value should not be null.

You can read more about the difference between HashTable and HashMap here.

What is the clear() method in Hashtable?

The clear() method of the Hashtable class removes all of the key and value entries from a specified Hashtable object. After calling this method, the Hashtable object becomes empty.

Syntax

public void clear()

This method doesn’t take any parameters and does not return a value.

Code

The code below shows how to use the clear() method.

import java.util.Hashtable;
class HashtableClearExample {
public static void main( String args[] ) {
Hashtable<Integer, String> numbers = new Hashtable<>();
numbers.put(1, "one");
numbers.put(2, "two");
System.out.println("Hashtable is : "+ numbers);
numbers.clear();
System.out.println("\nAfter Calling Clear method");
System.out.println("\nHashtable is : " + numbers);
}
}

Explanation

In the code above:

  • In line 1, we import the Hashtable class.

  • From lines 5 to 8, we create a Hashtable object and use the put() method to add two entries ({1=one, 2=two}) to the numbers object.

  • In line 11, we use the clear() method to remove all the entries from the numbers object. This makes the numbers empty.

  • In line 14, we print numbers to ensure that it is empty.

Free Resources