温馨提示×

hashmap putifabsent和put区别详解

小樊
112
2024-07-19 04:39:44
栏目: 编程语言

putIfAbsent和put都是用来向HashMap中添加元素的方法,但是它们之间有一些重要的区别。

  1. put方法是向HashMap中添加键值对的常用方法,如果指定的键已经存在于HashMap中,则会更新该键对应的值;如果键不存在,则会将该键值对添加到HashMap中。
HashMap<String, Integer> map = new HashMap<>();
map.put("key1", 1); //添加键值对"key1"->1
map.put("key1", 2); //更新键"key1"对应的值为2
  1. putIfAbsent方法是在键不存在时才会向HashMap中添加键值对,如果指定的键已经存在于HashMap中,则不做任何操作并返回原有的值。
HashMap<String, Integer> map = new HashMap<>();
map.put("key1", 1); 
Integer oldValue = map.putIfAbsent("key1", 2); //键"key1"已存在, oldValue为1
System.out.println(oldValue); //输出1
  1. putIfAbsent方法可以避免因为键已存在而意外覆盖原有值的情况,适用于需要确保某个键只有一个值的情况。
HashMap<String, List<Integer>> map = new HashMap<>();
map.putIfAbsent("key1", new ArrayList<>()); //如果键"key1"不存在,则添加一个空的ArrayList
map.get("key1").add(1); //向键"key1"对应的List中添加元素1

总的来说,put方法适用于普通的添加和更新操作,而putIfAbsent方法适用于需要确保键不存在时才添加的场景。

0