Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - Difference between replace and put for HashMap

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);
}

Is this correct? or should I use two times the put function?

question from:https://stackoverflow.com/questions/35297537/difference-between-replace-and-put-for-hashmap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


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:

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 is null.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...