hashMap中的put方法是放入数据,而:
HashMap putIfAbsent() 方法
也是放入数据,有什么区别呢?
putIfAbsent() 方法会先判断指定的键(key)是否存在,不存在则将键/值对插入到 HashMap 中。
putIfAbsent() 方法的语法为:
hashmap.putIfAbsent(K key, V value)
如果所指定的 key 已经在 HashMap 中存在,返回和这个 key 值对应的 value, 如果所指定的 key 不在 HashMap 中存在,则返回 null。
注意:如果指定 key 之前已经和一个 null 值相关联了 ,则该方法也返回 null。
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添