Java Hashtable - put() Method
The java.util.Hashtable.put() method is used to map the specified key to the specified value in the hashtable. Please note that neither the key nor the value can be null. If the key is already present in the map, the old value is replaced.
Syntax
public V put(K key, V value)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
key |
Specify the hashtable key. |
value |
Specify the hashtable value. |
Return Value
Returns previous value associated with given key, or null if it did not have one.
Exception
NA
Example:
In the example below, the java.util.Hashtable.put() method is used to map the specified key to the specified value in the given hashtable.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a hashtable Hashtable<Integer, String> Htable = new Hashtable<Integer, String>(); //populating hashtable Htable.put(101, "John"); Htable.put(102, "Marry"); Htable.put(103, "Kim"); Htable.put(104, "Jo"); //printing hash map System.out.println("Htable contains: " + Htable); //change a key-value pair Htable.put(103, "Ramesh"); //printing hash map System.out.println("Htable contains: " + Htable); } }
The output of the above code will be:
Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John} Htable contains: {104=Jo, 103=Ramesh, 102=Marry, 101=John}
❮ Java.util - Hashtable