Remove HashTable elements
We can remove elements from HashTable using methods provided in it
There are 2 methods listed below which can be used to remove elements from HashTable
Object remove(Object key)
Removes the mapping for the specified key from this HashTable if present.
Void clear()
Removes all of the mappings from this HashTable
Example
- import java.util.*;
- public class HashTableRemoveExample {
- public static void main(String args[]) {
- Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>();
- hashTable.put(1, "One");
- hashTable.put(2, "Two");
- hashTable.put(3, "Three");
- System.out.println("Initial HashTable");
- System.out.println(hashTable);
- hashTable.remove(1);
- System.out.println("HashTable after removing 1 element");
- System.out.println(hashTable);
- hashTable.clear();
- System.out.println("HashTable after removing all elements");
- System.out.println(hashTable);
- }
- }
import java.util.*; public class HashTableRemoveExample { public static void main(String args[]) { Hashtable<Integer,String> hashTable=new Hashtable<Integer,String>(); hashTable.put(1, "One"); hashTable.put(2, "Two"); hashTable.put(3, "Three"); System.out.println("Initial HashTable"); System.out.println(hashTable); hashTable.remove(1); System.out.println("HashTable after removing 1 element"); System.out.println(hashTable); hashTable.clear(); System.out.println("HashTable after removing all elements"); System.out.println(hashTable); } }
We can see that, clear() method has removed all elements in HashTable and remove() method has removed only specified element from the HashTable.