[問題] 一題SCJP的題目,有關equals()&hashcod()

看板java作者 (louis)時間14年前 (2011/12/06 04:03), 編輯推噓2(203)
留言5則, 5人參與, 最新討論串1/4 (看更多)
在練習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
應該是 hashCode 相等時,equals 不一定要回傳 true 吧
12/07 01:21, 3F

12/07 08:33, , 4F
其實 equals 底子裡也是用 ==
12/07 08:33, 4F

12/07 10:30, , 5F
equal 不是會比較快嗎?
12/07 10:30, 5F
文章代碼(AID): #1EtIEVQd (java)
討論串 (同標題文章)
文章代碼(AID): #1EtIEVQd (java)