我已经尝试环顾了一段时间,但找不到具体的答案,并且仍然无法准确理解 HashMap
的 compute
方法的作用。
我目前的理解是,compute
将允许您操作该值,但不能将其设置为新值(就像垃圾收集器必须删除旧值一样) object),而 put
只会删除旧对象并设置它(就像 x = new Something)。
如果我对此的理解是错误的,请告诉我,但无论如何,compute
方法通常更有效吗?我应该尽可能使用它而不是 put
还是只在某些情况下使用?
最佳答案
如果您想无条件设置新值,请使用put
。如果您想根据 map 中的现有值计算新值,请使用compute
。您可以选择将其更改为新值或将其从 map 中删除。
The default implementation is equivalent to performing the following steps for this map:
V oldValue = map.get(key); V newValue = remappingFunction.apply(key, oldValue); if (newValue != null) { map.put(key, newValue); } else if (oldValue != null || map.containsKey(key)) { map.remove(key); } return newValue;
它比简单的 put
更复杂:
- 它调用
get
来检索当前值。 - 它调用提供的重新映射函数将其转换为新值。
- 它要么调用
put
覆盖旧值,要么调用remove
删除旧值,具体取决于新值是否为 null。
由于最终它会调用 put
,因此 compute
的步骤更多且速度更慢。如果 put
满足您的需求 - 您不关心 map 中的内容,您只想将键设置为值 - 使用 put
。
关于java - 对于HashMap,使用compute()还是put()效率更高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70430071/