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

后端 未结 4 676
时光说笑
时光说笑 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: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.

提交回复
热议问题