[問題] 一題SCJP的題目,有關equals()&hashcod()
在練習SCJP的時候有一題一直搞不懂
Given:
Class SortOf{
String name;
int bal;
String code;
short rate;
public int hashCode(){
retrun (code.length()*bal);
}
public boolean equals(Object o){
//insert code here
}
}
Which of the following will fulfill the equals() and hashCode() contracts
for this class?
正確解答是:
c. return ((SortOf)o).code.length()*((SortOf)o).bal ==
this.code.length()*this.bal;
d. return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate ==
this.code.length()*this.bal*this.rate;
我了解為什麼c是對的,但我不懂為什麼d也是對的
我認為當兩個物件比較的時候,
當equals() returns true,兩個hashCode不一定會相等
所以d不應該是正確答案
不曉得有沒有人可以解答我的問題
為什麼d是對的
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 74.196.11.161
推
12/06 13:43, , 1F
12/06 13:43, 1F
→
12/06 21:49, , 2F
12/06 21:49, 2F
→
12/07 01:21, , 3F
12/07 01:21, 3F
推
12/07 08:33, , 4F
12/07 08:33, 4F
→
12/07 10:30, , 5F
12/07 10:30, 5F
討論串 (同標題文章)
以下文章回應了本文 (最舊先):
完整討論串 (本文為第 1 之 4 篇):