Home > Java > javaTutorial > Usage of put method in java

Usage of put method in java

下次还敢
Release: 2024-05-08 05:45:23
Original
1075 people have browsed it

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

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>
Copy after login

Notes

    ##Keys and values ​​can be of any object type.
  • If the key does not exist, the method will create the key and value and add them to the Map.
  • If the key exists, the method only updates the value and does not change the key.
  • If the value is
  • null, 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template