The output of the following code sample is:
{1--e=e2, 2--e1=e1}
package com.sid.practice;
import java.util.HashMap;
import
The Javadocs for HashMap state for the put
method:
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Hence, the key is not overwritten, only the value.
Actually, you got it backwards. The value was overridden. The key wasn't replaced since as far as HashMap
is concerned, e and e2 are identical.
Your output is {1--e=e2, 2--e1=e1}
:
key = e, value = "e2" (which overrode the old value "e")
key = e1, value = "e1"
The reason behind the output {1--e=e2, 2--e1=e1} is :
Map do not replaces key it only does so for value when there is match (present on the basis of key) in the existing Map. So applies in this case:
Here e is equal to e2 for Map. When Map search for location to put m.put(e2, "e2"); it goes to location where e--"e1" is present and replaces "e1" by "e2" and leaves the key i.e e in this case intact
The java.util.HashMap implementation does not replace the existing key when it is equal to the key supplied in the put() call. So, your third put() checks the existing contents of the map, finds an existing equal key and just updates the associated value.
This illustrates why equals() and hashCode() should generally take all properties into account as objects which are considered equal are considered interchangeable by many of the util classes.