Remove all Hashtable elements in Java
Deleting all values from a Hashtable is done in two different ways:
- By browsing the table and deleting the current element.
- By directly calling the method clear().
1) Browse and delete the key-value pairs of Hashtable
This method is useful when you don't want to remove all values by adding a statement that tests whether the item that is going to be deleted is affected. In this example we don't make exceptions, so we delete everything.
import java.util.Enumeration;
import java.util.Hashtable;
public class removeAll_Hashtable {
public static void main(String[] s) {
Hashtable table = new Hashtable();
table.put("1", "val1");
table.put("2", "val2");
table.put("3", "val3");
Enumeration e = table.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + table.get(key));
table.remove(key);
}
System.out.println("After deletion");
System.out.println(table);
}
}
Output:
3: val3
2: val2
1: val1
After deletion
{}
2) Delete key-value peers in calling the clear()
This method is finer because it saves us from writing code.
public void clear(): Empty the entire table so that it does not contain any items.
import java.util.Hashtable;
public class removeAll_Hashtable {
public static void main(String[] s) {
Hashtable table = new Hashtable();
table.put("1", "val1");
table.put("2", "val2");
table.put("3", "val3");
table.clear();
System.out.println("After calling clear()");
System.out.println(table);
}
}
Output:
After calling clear()
{}
References:
JavaDoc: Hashtable clear method
JavaDoc: Hashtable clear method