Quantcast
Viewing latest article 27
Browse Latest Browse All 485

Answer by Federico klez Culloca for Need to understand map.get() method after Overriding hashCode and equals in Java

HashMap's getchecks 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.


Viewing latest article 27
Browse Latest Browse All 485

Trending Articles