HashMap的replace和put之间的区别
我想通过使用HashMap
制作直方图,关键应该是延迟,该值是此延迟发生的次数。 如果已经存在的延迟有新的发生,我怀疑使用HashMap
replace
或HashMap
put
函数。
我是这样做的
int delay = (int) (loopcount-packetServed.getArrivalTime()); if(histogramType1.containsKey(delay)) { histogramType1.replace(delay, histogramType1.get(delay)+1); } else { histogramType1.put(delay, 1); }
它是否正确? 或者我应该使用put函数的两倍?
当有所需密钥的当前映射时, put
和replace
绝对没有区别。 来自replace
:
仅当指定键的当前映射到某个值时,才替换该条目的条目。
这意味着如果已经存在给定键的映射,则put
和replace
将以相同的方式更新映射。 两者都将返回与键关联的先前值。 但是,如果该键没有映射,则replace
将是no-op(将不执行任何操作),而put
仍将更新映射。
从Java 8开始,请注意您可以使用
histogramType1.merge(delay, 1, Integer::sum);
这将照顾每一个条件。 来自merge
:
如果指定的键尚未与值关联或与
null
关联,则将其与给定的非空值关联。 否则,将相关值替换为给定重映射函数的结果,或者如果结果为null
则删除。
在这种情况下,如果条目不存在,我们将创建条目delay -> 1
。 如果确实存在,则通过将值递增1来更新它。
在您的情况下,由于您首先检查该值是否包含在地图中,因此使用put
或replace
会导致相同的结果。
您可以根据更易读的内容使用其中之一。
如果您查看源代码,您可以看到以下内容(这是来自更新11,但可能没有太大变化):
替换 :
if ((e = getNode(hash(key), key)) != null) { V oldValue = e.value; e.value = value; afterNodeAccess(e); return oldValue; }
put (内部方法putVal):
//some code before this to find the node e (similar to getNode(hash(key))) if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) //onlyIfAbsent is false here e.value = value; afterNodeAccess(e); return oldValue; }
正如您所看到的,代码的相关部分基本上是相同的,因为onlyIfAbsent
对于put
是假的,因此总是会替换该值。
您可以使用以下方法validation其他人描述的行为:
public class Main { public static void main(String[] args) { Map map = new HashMap<>(); map.replace("a", "1"); System.out.println(map.get("a")); map.put("a", "1"); System.out.println(map.get("a")); map.replace("a", "2"); System.out.println(map.get("a")); } }