equals是Object的公有方法,那么我們通常都會(huì)在自己的類中重寫這個(gè)equals方法,同時(shí)必須重寫hasCode方法,知道為什么重寫equals方法必須重寫hasCode方法呢?
公司主營(yíng)業(yè)務(wù):成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。成都創(chuàng)新互聯(lián)公司是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來驚喜。成都創(chuàng)新互聯(lián)公司推出志丹免費(fèi)做網(wǎng)站回饋大家。
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code 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.
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code 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.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {@code 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.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
/**
* Indicates whether some other object is "equal to" this one.
* <p>
* The {@code equals} method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* {@code x}, {@code x.equals(x)} should return
* {@code true}.
* <li>It is <i>symmetric</i>: for any non-null reference values
* {@code x} and {@code y}, {@code x.equals(y)}
* should return {@code true} if and only if
* {@code y.equals(x)} returns {@code true}.
* <li>It is <i>transitive</i>: for any non-null reference values
* {@code x}, {@code y}, and {@code z}, if
* {@code x.equals(y)} returns {@code true} and
* {@code y.equals(z)} returns {@code true}, then
* {@code x.equals(z)} should return {@code true}.
* <li>It is <i>consistent</i>: for any non-null reference values
* {@code x} and {@code y}, multiple invocations of
* {@code x.equals(y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* objects is modified.
* <li>For any non-null reference value {@code x},
* {@code x.equals(null)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values {@code x} and
* {@code y}, this method returns {@code true} if and only
* if {@code x} and {@code y} refer to the same object
* ({@code x == y} has the value {@code true}).
* <p>
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
上面是Object對(duì)象中hasCode和equals的簽名和方法說明。
判斷一些對(duì)象是否等于當(dāng)前對(duì)象,實(shí)現(xiàn)在非空對(duì)象映射的等價(jià)關(guān)系。this==obj,由此可知,這是一個(gè)引用對(duì)象的等價(jià)判斷,只有在this和obj是指向用一個(gè)應(yīng)用時(shí)才返回true.這是判定實(shí)例的唯一性,我們通常使用equals時(shí),其實(shí)并不想判斷實(shí)例的唯一性,而是想要比較里面的幾個(gè)(自定義)屬性值是否相等,來判斷是否為同一個(gè)"東西"。
契約:
reflexive(自反性):x為非null時(shí),x.equals(x),一定返回true.
symmetric(對(duì)稱性):x,y都不為null,如果x.equals(y)返回true,那么y.equals(x).
transitive(傳遞性):x,y,z都不為null,如果x.equals(y),y.equals(z)返回true,那么x.equals(z)返回true.
consistent(一致性):對(duì)于任何非null的x\y,在沒有修改這些對(duì)象信息的前提下,多次調(diào)用下,x.equals(y)結(jié)果是一致的。
非null的x,x.equals(null)返回false.
下面是Book類的equals重寫實(shí)現(xiàn),通過bookN、bookName確定是否為同一本書(東西),而不是判斷兩個(gè)對(duì)象的引用是否為同一個(gè)。
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
return Objects.equal(bookNo, book.bookNo) &&
Objects.equal(bookName, book.bookName);
}
hasCode鍥約:
1.任何時(shí)候在沒有修改對(duì)象的前提下,多次調(diào)用同一個(gè)對(duì)象的hasCode方法,這個(gè)返回值必須是同一個(gè)Integer值。
2.如果兩個(gè)對(duì)象equals結(jié)果為true,那么hasCode的值必須相同。
3.如果兩個(gè)對(duì)象equals結(jié)果為false,那么hasCode就不一定不相同。
如果重寫equals方法時(shí),不去重寫hasCode方法,那么必然會(huì)違背第二條鍥約。所以每次hasCode必須跟隨equals重寫而重寫。
是不是有人就是問:如果就不重寫hasCode,不行嗎?就違背鍥約不可以嗎?只equals重寫有什么問題嗎?
那么這里就會(huì)引申出hasCode在集合中的應(yīng)用場(chǎng)景。
Java中的集合(Collection)有兩類,一類是List,再有一類是Set。前者集合內(nèi)的元素是有序的,元素可以重復(fù);后者元素?zé)o序,但元素不可重復(fù)。那么這里就有一個(gè)比較嚴(yán)重的問題了:要想保證元素不重復(fù),可兩個(gè)元素是否重復(fù)應(yīng)該依據(jù)什么來判斷呢?這就是 Object.equals方法了。但是,如果每增加一個(gè)元素就檢查一次,那么當(dāng)元素很多時(shí),后添加到集合中的元素比較的次數(shù)就非常多了。也就是說,如果集合中現(xiàn)在已經(jīng)有1000個(gè)元素,那么第1001個(gè)元素加入集合時(shí),它就要調(diào)用1000次equals方法。這顯然會(huì)大大降低效率。
于是,Java采用了哈希表的原理。哈希算法也稱為散列算法,是將數(shù)據(jù)依特定算法直接指定到一個(gè)地址上??梢赃@樣簡(jiǎn)單理解,hashCode方法實(shí)際上返回的就是對(duì)象存儲(chǔ)位置的映像。
當(dāng)集合中添加元素時(shí),先調(diào)用hasCode方法,如果這個(gè)位置沒有元素,那么就直接存儲(chǔ)在這里,如果有元素,那么再調(diào)用equals方法與新元素比較,如果相同不存了,如果不相同則說明發(fā)生碰撞(沖突),碰撞解決方法多樣,最終都會(huì)存儲(chǔ)在一個(gè)合適的位置。有了hasCode后,調(diào)用equals的次數(shù)大大降低,一般一兩次就搞定了。
擴(kuò)展的內(nèi)容有興趣可以自行深入學(xué)習(xí)。為什么系列采用簡(jiǎn)短,易懂方式歸納總結(jié)一些工作中、面試中常常出現(xiàn)的問題進(jìn)行解答。如果有錯(cuò)誤請(qǐng)及時(shí)聯(lián)系我,以免誤導(dǎo)他人。
文章標(biāo)題:為什么系列之重寫equals方法必須重寫hasCode方法?
當(dāng)前路徑:http://jinyejixie.com/article36/pdcjpg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、App開發(fā)、面包屑導(dǎo)航、網(wǎng)站設(shè)計(jì)公司、網(wǎng)站營(yíng)銷、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)