程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java equals 辦法與hashcode 辦法的深刻解析

Java equals 辦法與hashcode 辦法的深刻解析

編輯:關於JAVA

Java equals 辦法與hashcode 辦法的深刻解析。本站提示廣大學習愛好者:(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辦法來確保這個分歧性

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved