Difference between Replacement and Delivery for HashMap

I want to make a histogram using a HashMap , the key must be a delay, the value of which is the number of times this delay. I doubt using the HashMap replace or HashMap put function if the already existing delay has a new appearance.

I did it this way

 int delay = (int) (loopcount-packetServed.getArrivalTime()); if(histogramType1.containsKey(delay)) { histogramType1.replace(delay, histogramType1.get(delay)+1); } else { histogramType1.put(delay, 1); } 

It is right? or should I use the put function twice?

+8
java hashmap
source share
4 answers

There is no difference in put and replace when there is a current mapping for the required 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 this key, then the put and replace tags will update the map in the same way. Both will return the previous value associated with the key. However, if there is no mapping for this key, then replace will be no-op (will do nothing), while 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 all conditions. From merge :

If the specified key is not yet associated with the value or is associated with null , associates it with the specified non-empty value. Otherwise, the associated value with the results of the given remapping function is replaced or deleted if the result is null .

In this case, we create a delay -> 1 record if the record does not exist. If it exists, it is updated by increasing the value by 1.

+11
source share

In your case, since you are first checking to see if this value is on the map, using put or replace produces the same result.

You can use either based on what is more readable to you.

+2
source share

If you look at the sources, you will see the following (this is from version 11, but probably has not changed much):

replace

 if ((e = getNode(hash(key), key)) != null) { V oldValue = e.value; e.value = value; afterNodeAccess(e); return oldValue; } 

put (internal putVal method):

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

As you can see, the relevant parts of the code do basically the same thing, since onlyIfAbsent is false for put and therefore will always replace the value.

+1
source share

You can test the behavior described by others as follows:

 public class Main { public static void main(String[] args) { Map<String, String> 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")); } } 
0
source share

All Articles