The put method in Java is used to add or update key-value pairs in Map. It adds the specified key and value to the Map, or updates its corresponding value if the key already exists.
Usage of put method in Java
In Java, put method is used to add to Map data structure Or update key-value pairs. Map is an associative array where each key corresponds to a value.
Usage
put(key, value)
method adds the specified key and value to the Map. If the key already exists in the Map, the value corresponding to the key will be updated.
Parameters
key
: The key to be added to the Map. value
: The value to be associated with this key. Return value
If the key already exists in the Map, the method returns the value previously associated with the key. Otherwise, the method returns null
.
Example
<code class="java">Map<String, String> names = new HashMap<>(); names.put("John", "Doe"); // 添加键值对 names.put("John", "Smith"); // 更新键值对</code>
Notes
, the method will remove the key from the Map.
The above is the detailed content of Usage of put method in java. For more information, please follow other related articles on the PHP Chinese website!