作者louisyu (louis)
看板java
標題[問題] 一題SCJP的題目,有關equals()&hashcod()
時間Tue Dec 6 04:03:41 2011
在練習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
推 AI3767:可以把其它錯誤的答案一起列出來比較嗎? :) 12/06 13:43
→ awert:這題目還可以更爛一點... 12/06 21:49
→ tkcn:應該是 hashCode 相等時,equals 不一定要回傳 true 吧 12/07 01:21
推 MephistoH:其實 equals 底子裡也是用 == 12/07 08:33
→ glennchen:equal 不是會比較快嗎? 12/07 10:30