In the last tutorial we have seen how to remove a mapping from Hashtable based on key. In this tutorial we will learn how to remove all the mappings from Hashtable and make it empty.
Example
Method used in the below program: clear()
public void clear()
: Clears this hashtable so that it contains no keys.
import java.util.Hashtable; public class RemoveAllExample { public static void main(String[] args) { // Creating a Hashtable Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); // Adding Key and Value pairs to Hashtable hashtable.put(11,"AA"); hashtable.put(22,"BB"); hashtable.put(33,"CC"); hashtable.put(44,"DD"); hashtable.put(55,"EE"); // Before remove System.out.println("Hashtable contains:" + hashtable); // Removing all mappings hashtable.clear(); // After remove System.out.println("After remove:"); System.out.println("Hashtable contains: " + hashtable); } }
Output:
Hashtable contains:{55=EE, 44=DD, 33=CC, 22=BB, 11=AA} After remove: Hashtable contains: {}
As you can see all the key-value mappings have been removed from Hashtable and it became empty after calling clear() method.
Leave a Reply