您好,登錄后才能下訂單哦!
equals是Object的公有方法,那么我們通常都會在自己的類中重寫這個equals方法,同時必須重寫hasCode方法,知道為什么重寫equals方法必須重寫hasCode方法呢?
/**
* 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對象中hasCode和equals的簽名和方法說明。
判斷一些對象是否等于當前對象,實現在非空對象映射的等價關系。this==obj,由此可知,這是一個引用對象的等價判斷,只有在this和obj是指向用一個應用時才返回true.這是判定實例的唯一性,我們通常使用equals時,其實并不想判斷實例的唯一性,而是想要比較里面的幾個(自定義)屬性值是否相等,來判斷是否為同一個"東西"。
契約:
reflexive(自反性):x為非null時,x.equals(x),一定返回true.
symmetric(對稱性):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(一致性):對于任何非null的x\y,在沒有修改這些對象信息的前提下,多次調用下,x.equals(y)結果是一致的。
非null的x,x.equals(null)返回false.
下面是Book類的equals重寫實現,通過bookN、bookName確定是否為同一本書(東西),而不是判斷兩個對象的引用是否為同一個。
@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.任何時候在沒有修改對象的前提下,多次調用同一個對象的hasCode方法,這個返回值必須是同一個Integer值。
2.如果兩個對象equals結果為true,那么hasCode的值必須相同。
3.如果兩個對象equals結果為false,那么hasCode就不一定不相同。
如果重寫equals方法時,不去重寫hasCode方法,那么必然會違背第二條鍥約。所以每次hasCode必須跟隨equals重寫而重寫。
是不是有人就是問:如果就不重寫hasCode,不行嗎?就違背鍥約不可以嗎?只equals重寫有什么問題嗎?
那么這里就會引申出hasCode在集合中的應用場景。
Java中的集合(Collection)有兩類,一類是List,再有一類是Set。前者集合內的元素是有序的,元素可以重復;后者元素無序,但元素不可重復。那么這里就有一個比較嚴重的問題了:要想保證元素不重復,可兩個元素是否重復應該依據什么來判斷呢?這就是 Object.equals方法了。但是,如果每增加一個元素就檢查一次,那么當元素很多時,后添加到集合中的元素比較的次數就非常多了。也就是說,如果集合中現在已經有1000個元素,那么第1001個元素加入集合時,它就要調用1000次equals方法。這顯然會大大降低效率。
于是,Java采用了哈希表的原理。哈希算法也稱為散列算法,是將數據依特定算法直接指定到一個地址上。可以這樣簡單理解,hashCode方法實際上返回的就是對象存儲位置的映像。
當集合中添加元素時,先調用hasCode方法,如果這個位置沒有元素,那么就直接存儲在這里,如果有元素,那么再調用equals方法與新元素比較,如果相同不存了,如果不相同則說明發生碰撞(沖突),碰撞解決方法多樣,最終都會存儲在一個合適的位置。有了hasCode后,調用equals的次數大大降低,一般一兩次就搞定了。
擴展的內容有興趣可以自行深入學習。為什么系列采用簡短,易懂方式歸納總結一些工作中、面試中常常出現的問題進行解答。如果有錯誤請及時聯系我,以免誤導他人。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。