Java HashMap return value not confirming with my understanding of equals and hashcode

后端 未结 4 677
时光说笑
时光说笑 2021-01-23 08:01

The output of the following code sample is:

{1--e=e2, 2--e1=e1}

package com.sid.practice;

import java.util.HashMap;
import         


        
相关标签:
4条回答
  • 2021-01-23 08:06

    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.

    0 讨论(0)
  • 2021-01-23 08:14

    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" 
    
    0 讨论(0)
  • 2021-01-23 08:27

    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

    0 讨论(0)
  • 2021-01-23 08:30

    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.

    0 讨论(0)
提交回复
热议问题