Question

Need to understand map.get() method after Overriding hashCode and equals in Java

I have overridden the hashCode and equals methods as below, and I want to understand the implementation of Map get method.

public class Student{
    String name;

    Student(String s){
        this.name = s;
    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        return 111;
    }

    public static void main(String[] args) {
        Map<Student,String> map=new HashMap<>();
        Student ob1=new Student("A");
        Student ob2=new Student("B");
        map.put(ob1,"A");
        map.put(ob2,"B");
        System.out.println(map.get(ob1));
    }
}

I tried running map.get() expecting null result because the key will never be found because the equals() method will always return false but I am getting the result as A in this case.

 5  142  5
1 Jan 1970

Solution

 12

HashMap's get checks for equality with == before using equals.

So the fact that you're using the same object you used as a key (rather than an object with the same content but a different reference) makes get work.

If you try this way

public static void main(String[] args) {
    Map<Student,String> map=new HashMap<>();
    Student ob1=new Student("A");
    Student ob2=new Student("B");
    Student keyTest = new Student("A");
    map.put(ob1,"A");
    map.put(ob2,"B");
    System.out.println(map.get(keyTest)); //different key here
}

it prints null.

2024-07-06
Federico klez Culloca