HashMap如何在不调用equals方法的情况下替换键的值

Sum*_*gal 4 java equals hashmap

public class Test
{
    public static void main(String[] args) {
        Employee e1=new Employee(1);
        Employee e2=new Employee(1);
        HashMap<Employee,String> map=new HashMap<Employee,String>();
        map.put(e1, "A");
        map.put(e1, "B");
        map.put(e2, "C");
        }
}
class Employee{
    private int id;
     Employee(int id){
         this.id=id;
     }

@Override
public int hashCode() {
    System.out.println("hascode is ="+this.id);
    return  this.id;
}
@Override
    public boolean equals(Object obj) {
    System.out.println("Equals");
        return super.equals(obj);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我再次放置相同的对象e1时,不会调用equals()方法,那么如何在没有在地图的现有对象中检查的情况下为键e1替换值B?(我认为这是equals方法的工作)

Erw*_*idt 5

Object.equals方法的契约要求实现是反身的:

它是自反的:对于任何非空引用值x,x.equals(x) 应该返回true.

这意味着HashMap允许实现,实际上确实总是使用==first 进行比较,并且只有在不进行比较时才调用该equals方法true.因此,如果e1使用完全相同的对象替换键的值e1,它只使用==比较并且永远不会调用该equals方法.

如果查看HashMap为键设置值的实现,您会发现此语句的变体两次:

if (e.hash == hash &&
    ((k = e.key) == key || (key != null && key.equals(k))))
    break;
Run Code Online (Sandbox Code Playgroud)

(一次用于哈希桶中的第一个密钥,然后在循环中迭代哈希桶中的任何其他密钥)