我已經覆蓋了下面的hashCode
和equals
方法,我想了解Map get方法的實現。
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));
}
}
我試著運行map.get()
,但卻得到了null
的結果,因為equals()
方法總是返回false,所以永遠找不到鍵,但在這種情況下,我得到的結果是A
。
在使用
equals
之前,HashMap
的get
檢查是否與==
相等。因此,您使用的對象與用作鍵的對象相同(而不是具有相同內容但引用不同的對象),這一事實使
get
起作用。如果你試著這樣做
它打印
null
。