Java Dictionary - put() Method
The java.util.Dictionary.put() method is used to map the specified key to the specified value in this dictionary. Neither the key nor the value can be null. If this dictionary already contains an entry for the specified key, the value already in this dictionary for that key is returned, after modifying the entry to contain the new element. If this dictionary does not already have an entry for the specified key, an entry is created for the specified key and value, and null is returned.
Syntax
public abstract 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 value. |
Return Value
Returns the previous value to which the key was mapped in this dictionary, or null if the key did not have a previous mapping.
Exception
Throws NullPointerException, if the key or value is null.
Example:
In the example below, the java.util.Dictionary.put() method is used to map the specified key to the specified value in the given dictionary.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a dictionary Dictionary<Integer, String> Dict = new Hashtable<Integer, String>(); //populating dictionary Dict.put(101, "John"); Dict.put(102, "Marry"); Dict.put(103, "Kim"); Dict.put(104, "Lee"); //printing the content of the dictionary System.out.println("Dict contains: " + Dict); //changing the mapping for key 104 Dict.put(104, "Sam"); //adding a new key 105 Dict.put(105, "Jo"); //printing the content of the dictionary System.out.println("Dict contains: " + Dict); } }
The output of the above code will be:
Dict contains: {104=Lee, 103=Kim, 102=Marry, 101=John} Dict contains: {105=Jo, 104=Sam, 103=Kim, 102=Marry, 101=John}
❮ Java.util - Dictionary