Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading