Hashtable
Remove all mappings from Hashtable example
With this example we are going to demonstrate how to remove all mappings from a Hashtable, that means removing all key value pairs from the Hashtable. In short, to remove all mappings from a Hashtable you should:
- Create a new Hashtable.
- Populate the hashtable with elements, using
put(K key, V value)
API method of Hashtable. - Invoke the
clear()
API method of Hashtable. It removes all keys and their corresponding values from the hashtable, so that the Hashtable contains no keys.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.Hashtable; public class ClearHashtable { public static void main(String[] args) { // Create a Hashtable and populate it with elements Hashtable hashtable = new Hashtable(); hashtable.put("key_1","value_1"); hashtable.put("key_2","value_2"); hashtable.put("key_3","value_3"); System.out.println("Hashtable contains : " + hashtable); // void clear method() removes all mappings of Hashtable class hashtable.clear(); System.out.println("Hashtable contains : " + hashtable); } }
Output:
Hashtable contains : {key_3=value_3, key_2=value_2, key_1=value_1}
Hashtable contains : {}
This was an example of how to remove all mappings from a Hashtable in Java.