爲什麼系列之重寫equals方法必須重寫hasCode方法?

Object源代碼及註釋

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的簽名和方法說明。

爲啥重寫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方法

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的次數大大降低,一般一兩次就搞定了。

擴展的內容有興趣可以自行深入學習。爲什麼系列採用簡短,易懂方式歸納總結一些工作中、面試中常常出現的問題進行解答。如果有錯誤請及時聯繫我,以免誤導他人。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章