1. 程式人生 > >Java equals 方法與hashcode 方法的深入解析

Java equals 方法與hashcode 方法的深入解析

PS:本文使用jdk1.7
解析
1.Object類 的equals 方法

複製程式碼程式碼如下:
   /**
     * 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的equals方法,採用== 進行比較,只是比較物件的引用,如果引用的物件相同,那麼就返回true. 
看註釋,Object的equals方法,具有如下特性
1.reflexive-自反性  

 x.equals(x)  return true
2.symmetric-對稱性
x.equals(y)  return true
y.equals(x)  return true
3.transitive-傳遞性
x.equals(y)  return true
y.equals(z)  return true
x.equals(z)  return true
4.consistent-一致性
x.equals(y)  return true //那麼不管呼叫多少次,肯定都是返回true
5.與null的比較
x.equals(null) return false //對於none-null的x物件,每次必然返回false
6.於hashcode的關係
     * 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.
需要注意的是,一般來說,如果重寫了equals方法,都必須要重寫hashcode方法,
來確保具有相同引用的物件,能夠具有同樣的hashcode值
好了,看到這裡,我們就明白了,為什麼重寫了equals方法,一般來說就需要重寫hashcode方法,
雖然這個不是強制性的,但是如果不能保證相同的引用物件,沒有相同的hashcode,會對系統留下很大隱患
2.String類的equals方法

複製程式碼程式碼如下:
   /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }


看原始碼,我們可以發現,這個比較分為兩部分
1.先比較是否引用同一物件
2.如果引用物件不同,是否兩個String的content相同
3,String 類的hashcode 方法

複製程式碼程式碼如下:
    /**
     * Returns a hash code for this string. The hash code for a
     * <code>String</code> object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using <code>int</code> arithmetic, where <code>s[i]</code> is the
     * <i>i</i>th character of the string, <code>n</code> is the length of
     * the string, and <code>^</code> indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }


可以看到hashcode的計算公式為:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 
因此,對於同一個String,得出的hashcode必然是一致的
另外,對於空的字串,hashcode的值是0

 

小結
至此,我們可以對本文開頭的疑問做一個小結.
1.字串比較時用的什麼方法,內部實現如何?
使用equals方法,先比較引用是否相同,後比較內容是否一致.

2.hashcode的作用,以及重寫equal方法,為什麼要重寫hashcode方法?
hashcode是系統用來快速檢索物件而使用,equals方法是用來判斷引用的物件是否一致,所以,當引用物件一致時,必須要確保其hashcode也一致,因此需要重寫hashcode方法來確保這個一致性 

 

 
郝斌.java視訊教程107集全
傳智播客 JavaEE+javaweb+Hadoop大資料就業班
JAVA系列視訊培訓教程JAVA品牌培訓機構最新課程全套
[JAVA] JavaSE實戰專案【LOL工具箱+憤怒的小鳥拼圖】 視訊教程 教學視訊 百度網盤下載
[JAVA] 原始碼教育Spring MVC 框架搭建及入門詳解 視訊教程 教學視訊 百度網盤下載
[JAVA] JavaWeb第三季視訊教程下載 視訊教程 教學視訊 百度網盤下載
[JAVA] 吉林大學 java程式設計基礎 全30講 視訊教程 教學視訊 百度網盤下載
[JAVA] 西安交通大學 JAVA語言 32講 王志文主講 視訊教程
[JAVA] Java Hibernate5 140課最新視訊教程 Java Hibernate5完全實戰視訊教程
煉數成金 大型分散式系統案例實戰 十四周大型分散式系統學習視訊教程