问题描述
Java8引入了那些不错的方法 getOrDefault()
和 putIfAbsent()
,允许编写如下代码:
Java8 introduced those nice methods getOrDefault()
and putIfAbsent()
, allowing to write code like:
Map<Foo, List<Bar>> itemsByFoo = ...
List<Bar> bars = itemsByFoo.getOrDefault(key, new ArrayList<>());
bars.add(someNewBar);
现在我想知道是否有充分的事实理由:
Now I am wondering if there are good factual reasons to either do:
itemsByFoo.put(key, bars);
或
itemsByFoo.putIfAbsent(key, bars);
两者都有效:
- $ b当向列表中添加元素时,$ b
- 选项1可能会执行大量不必要的put调用
- option2可能会做很多不必要的事情contains 在为新键添加新条目时调用占主导地位
- option 1 might do a lot of unnecessary "put" calls when adding elements to lists happens often
- option2 might do a lot of unnecessary "containsKey" calls when adding new entries for new keys is dominant
SO:这是很好的理由去选项1或选项2总是?
SO: are the good reasons to go for option 1 or option 2 "always"?
推荐答案
getOrDefault
是如果您想在不修改地图的情况下使用替代值来获取缺席值,则表示合适。如果您想为缺席密钥添加新值,您可以在一次操作中正确执行。
getOrDefault
is suitable if you want to use a stand-in for an absent value without modifying the map. If you want to add a new value for absent keys, you can do it right in one operation.
List<Bar> bars = itemsByFoo.computeIfAbsent(key, x -> new ArrayList<>());
bars.add(someNewBar);
甚至
itemsByFoo.computeIfAbsent(key, x -> new ArrayList<>()).add(someNewBar);
在最好的情况下,当被地图$ c覆盖时$ c>实现,就像
HashMap
一样,这将只承担一次哈希查找。
In the best case, when being overridden by the Map
implementation, like with HashMap
, this will bear a single hash lookup only.
不是 putIfAbsent
在使用默认
实现时只进行两次查找,但当然,大多数 Map
实现将为它提供单个查找实现。尽管如此, getOrDefault
和 putIfAbsent
的组合仍会在最佳情况下进行两次查找,而优化的 computeIfAbsent
只有一个。
Not that putIfAbsent
only bears two lookups when using the default
implementation, but, of course, most Map
implementations will provide a single lookup implementation for it. Still, the combination of getOrDefault
and putIfAbsent
would still bear two lookups in the best case, whereas an optimized computeIfAbsent
does only one.
这篇关于在使用getOrDefault()之后我应该使用put()还是putIfAbsent()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!