日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java中的equals方法+hashCode方法

發(fā)布時間:2023/12/3 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java中的equals方法+hashCode方法 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

【0】README

0.1)以下內(nèi)容均為原創(chuàng),包括源代碼, 旨在理清 equals 和 hashCode 方法的 實現(xiàn)原理
0.2) for full resource code, please visit
https://github.com/pacosonTang/core-java-volume/blob/master/chapter13/EqualsHashCodeTest.java

【1】equals 方法

1.1)父類Object中的equals 方法, 它本身比較的就是兩個對象的內(nèi)存地址是否相等(Object.equals 源碼):

1.2)自定義類中,如果希望對象中各個成員變量 分別相等,則它們的equals 方法 返回 true, 則:


【2】hashCode 方法(String.hashCode 源碼)


2.1)而 Object.hashCode 的返回值:
2.2)以下內(nèi)容轉(zhuǎn)自 API:http://docs.oracle.com/javase/8/docs/api/

The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java? programming language.)
  • 2.2.1)譯文如下:
  • hashCode的常規(guī)約定是:
    • 1)對同一個對象的不止一次調(diào)用, hashCode 方法必須返回同一個整型值,假如 在equals方法 比較兩個對象的過程中 沒有信息被修改的話。當對同一個應(yīng)用的不同執(zhí)行,這個值(hashCode)不需要保持一致;可以不一樣;
    • 2)如果兩個對象在 equals 方法中被認為相等, 則 上述兩個對象的 hashCode 也應(yīng)該返回相同的值;
    • 3)不做要求的是,如果 java.lang.Object.equals 認為兩個對象不相等,則 兩個對象的 hashCode 方法 返回 不同的值。然而, 編碼者應(yīng)該注意的是,對不相等對象產(chǎn)生的不同整型值(hashCode) 可能會影響 哈希表的性能;
  • Object.hashCode 的返回值:(對象的內(nèi)部地址值)
    • 要做到盡可能合理實用, Object.hashCode 方法對不同的對象產(chǎn)生不同的整型值。(這往往是通過 將對象的內(nèi)部地址值轉(zhuǎn)換為 整型值來實現(xiàn)的, 但這個實現(xiàn)技術(shù)不是 Java 編程語言硬性要求的)。

2.3) 我們再來看 Object.hashCode 的源碼:

for detailed native keyword , please visit http://blog.csdn.net/pacosonswjtu/article/details/50312333

總結(jié)

以上是生活随笔為你收集整理的java中的equals方法+hashCode方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。