equals與hashcode

來源:互聯網
上載者:User

預設的equal實現:
Object類裡定義的equal只是引用的判斷,如果二個執行個體的引用不一樣,就認為邏輯上也不一樣。
equal定製實現:
但是實際存在二個執行個體不一樣,但是邏輯上是一樣的。比如一些值對象的類Date,還比如oauth2裡面取回的使用者,只要這些使用者物件的uid是一樣的就認為邏輯相等。
關鍵詞:邏輯相同

equal使用getClass:不使用instanceOf 而使用getClass比較type是因為instanceOf會破壞對等性,但是getClass的缺點是只能相同的類比較。

The contract of equals mentions that it must be symmetric. This means that a.equals(b) if b.equals(a).
That's
the reason why instanceof is usually not used in equals (unless the
class is final). Indeed, if some subclass of Book (ComicsBook for
example) overrides equals to test that the other object is also an
instance of ComicsBook, you'll be in a situation where a Book instance
is equal to a ComicsBook instance, but a ComicsBook instance is not
equal to a Book instance.
You should thus (except when the class is final or in some other rare cases) rather compare the classes of the two objects:
if (this.getClass() != o.getClass()) {
    return false;
}
BTW, that's what Eclipse does when it generates hashCode and equals methods.

預設的hashcode實現:
Object類裡定義hashcode為每個執行個體返回的值都不一樣(public native hashcode();)hashcode 是一個外部調用,為了保證不一樣,很可能由執行個體的地址產生。
hashcode定製實現:
隨著equal的定製實現而實現。如果存在二個執行個體邏輯相等的情境而重寫了equal方法,那麼hashcode也應該使用equal中用到的屬性重寫。保證邏輯上相等的對象,hashcode也相等。注意,規範並沒有規定不同的執行個體有不同的hashcode. 所以不同的執行個體是可以有相同的hashcode。比如在hashmap,hashset的get/add的實現中,可能key的hashcode與桶裡面的某個元素的hashcode相等,所以,並不能由hashcode就判定桶裡一定包含了這個key,而應該進一步判斷equal。邏輯上不相等的對象最好擁有不相等的hashcode(規範上可以相等,但是考慮到散列的效能,應該盡量不相等)

 

 

hashmap的使用:
如果有某個需求要求判斷某個字串是否包含黑詞, 可以將黑詞放到hashmap裡. 將字串根據黑詞列表的長度進行切分. 然後利用hash命中黑詞的時間複雜度=常量來判斷是否有黑詞.這比使用indexof遍曆黑詞效率高很多.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.