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

看板java作者 (Alien)時間12年前 (2011/12/07 09:29), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/4 (看更多)
※ 引述《louisyu (louis)》之銘言: : 在練習SCJP的時候有一題一直搞不懂 [43] : 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是對的 你明白所謂 equals 與 hashcode 的 contract 是什麼意思嗎? 指的是:如果 equals 的話,hashcode 一定要一樣。(反之未必) 再比對上面的答案,你明白了嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 183.179.61.91

12/07 09:49, , 1F
Inheritance contract正解,其實去看Object的api就可以了解
12/07 09:49, 1F
文章代碼(AID): #1Eti5XZL (java)
討論串 (同標題文章)
文章代碼(AID): #1Eti5XZL (java)