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
.