Java HashMap put() Method
The put() method inserts the specified key/value pair into the HashMap.
The syntax of the put() method is:
hashmap.put(K key,V value)
Note:hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
- value - the value
Return Value
If a value corresponding to the inserted key already exists, the value replacement operation is performed and the old value is returned. If it does not exist, the insertion is performed and null is returned.
Example
The following example demonstrates the use of the put() method (when the value corresponding to the key does not exist):
Example
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
}
}
Running the above program produces the following output:
HashMap: {1=Google, 2=Example, 3=Taobao}
In the above example, we created a HashMap named sites, and then used the put() method to insert the key/value mapping into this HashMap.
Inserting multiple key/value pairsJava HashMap putAll() Method。
Note:Each entry is inserted into the HashMap randomly.
Example of inserting when the value corresponding to the key already exists:
Example
class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> sites = new HashMap<>();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "Example");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// Add a duplicate key element
String value = sites.put(1, "Weibo");
System.out.println("Modified HashMap: " + sites);
// View the replaced value
System.out.println("Replaced value: " + value);
}
}
Running the above program produces the following output:
修改后的 HashMap: {1=Weibo, 2=Example, 3=Taobao}
替换的值: Google
Other Extensions
Java HashMap