HashMap的replace和put的区别 [英] Difference between replace and put for HashMap
问题描述
我想用HashMap
做一个直方图,关键应该是延迟,这个值是延迟发生的次数.如果已经存在的延迟有新的发生,我怀疑使用 HashMap
replace
或 HashMap
put
函数.我是这样做的:
I want to make a histogram by using a HashMap
, the key should be the delay, the value the amount of times this delay occurs. I am doubting to use the HashMap
replace
or the HashMap
put
function if an already existing delay has an new occurence. I did it by this way:
int delay = (int) (loopcount-packetServed.getArrivalTime());
if(histogramType1.containsKey(delay)) {
histogramType1.replace(delay, histogramType1.get(delay) + 1);
} else {
histogramType1.put(delay, 1);
}
这是正确的吗?还是我应该使用两次 put 函数?
Is this correct? or should I use two times the put function?
推荐答案
put
和 replace
当需要的键有当前映射时绝对没有区别.来自 replace
:
There is absolutely no difference in put
and replace
when there is a current mapping for the wanted key. From replace
:
仅当当前映射到某个值时才替换指定键的条目.
Replaces the entry for the specified key only if it is currently mapped to some value.
这意味着如果给定键已经有映射,put
和 replace
都会以相同的方式更新映射.两者都将返回与键关联的先前值.但是,如果该键没有映射,则 replace
将是空操作(什么都不做),而 put
仍会更新映射.
This means that if there is already a mapping for the given key, both put
and replace
will update the map in the same way. Both will also return the previous value associated with the key. However, if there is no mapping for that key, then replace
will be a no-op (will do nothing) whereas put
will still update the map.
从 Java 8 开始,注意你可以直接使用
Starting with Java 8, note that you can just use
histogramType1.merge(delay, 1, Integer::sum);
这将处理所有情况.来自 合并
:
This will take care of every condition. From merge
:
如果指定的键尚未与值相关联或与 null
相关联,则将其与给定的非空值相关联.否则,用给定重映射函数的结果替换关联值,如果结果为 null
,则删除.
If the specified key is not already associated with a value or is associated with
null
, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result isnull
.
在这种情况下,我们正在创建条目 delay ->1
如果条目不存在.如果确实存在,则通过将值增加 1 来更新它.
In this case, we are creating the entry delay -> 1
if the entry didn't exist. If it did exist, it is updated by incrementing the value by 1.
这篇关于HashMap的replace和put的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!