Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 666
StudentX Avatar asked Feb 09 '16 16:02

StudentX


People also ask

Does HashMap put replace Java?

Yes. If a mapping to the specified key already exists, the old value will be replaced (and returned). See Hashtable.

Can we replace key in HashMap?

You cannot rename/modify the hashmap key once added. Only way is to delete/remove the key and insert with new key and value pair. Reason : In hashmap internal implementation the Hashmap key modifier marked as final . this is the best answer in my opinion since it's not possible to rename a key.

Does HashMap allow duplicate keys?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.


2 Answers

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.

like image 103
Tunaki Avatar answered Sep 28 '22 08:09

Tunaki


In your case, since you first check if the value is contained in the map, using put or replace leads to the same result.

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

like image 37
Jean Logeart Avatar answered Sep 28 '22 08:09

Jean Logeart