Add Items to Hashtable in Java
The program below shows how to easily add items to Hashtable using the java.util.Hashtable.put() of the Hashtable.public V put(K key, V val): This method takes two parameters, one for the key and one for the value associated with that key. The put() method returns the old value of the corresponding key, or null if it doesn't already have a value.
An exception is thrown NullPointerException if the key or value is null.
In this example, key-value pairs are inserted and then the table is traversed with the java enumeration. e and as long as there are elements (in the code with the hasMoreElements()) we retrieve the key with the method nextElement() and print it and its value.
import java.util.Enumeration;
import java.util.Hashtable;
public class main {
public static void main(String[] s) {
Hashtable< String, String> ht = new Hashtable< String, String> ();
ht.put("k1", "a");
ht.put("k2", "b");
ht.put("k3", "c");
ht.put("k4", "d");
Object ancien_valeur = ht.put("k4", "e");Runtime:
System.out.println("old value of the k4 key is:"+ancien_valeur);
Enumeration e = ht.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " : " + ht.get(key));
}
}
}
old value of the k4 key is:eResources:
k4: d
k3: c
k2: b
k1: a
Tutorials Point: java.util.Hashtable.put() Method