我發現了類似的問題,但目前爲止他們都沒有真正幫助我(這可能意味着我做錯了某些事情,這就是爲什麼我在這裏)。使用對象的實例作爲HashMap鍵
我有一個HashMap Map<Integer, List<Book>>
是應該有一個Student
的ID
的關鍵,他有在他身上的價值Book
列表。雖然只有通過ID
作爲關鍵工作,但我覺得它不是一個面向對象的方法,我應該使用Student
作爲關鍵(因此它看起來像這樣:Map<Student, List<Book>>
)。我試圖使用它,但當我試圖返回給定的Student
的Book
列表時,我收到了一堆錯誤,很可能是因爲找不到Student
。我的教授建議我@Override
Java的hashCode
和equals
方法,這是有道理的,因爲這是如何比較鍵,但我沒有在那成功(我不知道我究竟需要比較才能看到兩個Student
是一樣的;據推測,他們的ID
應該單獨工作)。這裏是重寫的方法:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
return true;
}
我在做什麼錯?任何你可以解決的問題都會非常有幫助。提前致謝!
的錯誤是在其他地方。發佈一個完整的重現問題的最小例子。 –
'if(id!= other.id) return false; return true;'你爲什麼喜歡這個'return id.equals(other.id);'? –