How does a HashMap replace a key value without invoking the equals method

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);
    }
}

When I put the same e1 object again, the equals () method will not be called, then how to replace the B value for the e1 key without checking the existing objects on the map? (which, I suppose, is the task of the equality method)

+4
source share
1 answer

The method contract Object.equalsrequires that the implementation be reflective:

This is reflective: for any nonzero reference value x, x.equals(x)should return true.

, HashMap , , == equals, true. , e1 e1, == equals.

HashMap, , :

if (e.hash == hash &&
    ((k = e.key) == key || (key != null && key.equals(k))))
    break;

( -, -)

+5

Source: https://habr.com/ru/post/1676886/


All Articles