最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2013年07月09日 18:37:16   作者:  
面試時經常會問起字符串比較相關的問題,比如:字符串比較時用的什么方法,內部實現(xiàn)如何?hashcode的作用,以及重寫equal方法,為什么要重寫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,會對系統(tǒng)留下很大隱患
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;
    }

看源碼,我們可以發(fā)現(xiàn),這個比較分為兩部分
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.字符串比較時用的什么方法,內部實現(xiàn)如何?
使用equals方法,先比較引用是否相同,后比較內容是否一致.

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

相關文章

  • 詳解Java實現(xiàn)多線程的三種方式

    詳解Java實現(xiàn)多線程的三種方式

    這篇文章主要為大家詳細介紹了Java實現(xiàn)多線程的三種方式,感興趣的小伙伴們可以參考一下
    2016-03-03
  • Java多線程之同步工具類CyclicBarrier

    Java多線程之同步工具類CyclicBarrier

    這篇文章主要介紹Java多線程之同步工具類CyclicBarrier,它是一個同步工具類,它允許一組線程互相等待,直到達到某個公共屏障點,支持一個可選的Runnable命令,在一組線程中的最后一個線程到達之后,該命令只在每個屏障點運行一次。下面來看文章具體內容
    2021-10-10
  • java8升級到java17的兼容性分析與遷移指南

    java8升級到java17的兼容性分析與遷移指南

    這篇文章主要為大家詳細介紹了從?Java?8?升級到?Java?17?的詳細分析和遷移步驟,包括代碼修改建議,依賴更新和配置調整,有需要的小伙伴可以參考一下
    2025-04-04
  • Java List按照某字段去重的使用示例

    Java List按照某字段去重的使用示例

    在Java開發(fā)中,我們經常會面臨對List中對象屬性去重的需求,本文主要介紹了Java List按照某字段去重的使用示例,具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • Java代碼編譯和反編譯的那些事兒

    Java代碼編譯和反編譯的那些事兒

    這篇文章主要給大家介紹了關于Java代碼編譯和反編譯的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-05-05
  • 在IDEA中如何設置最多顯示文件標簽個數(shù)

    在IDEA中如何設置最多顯示文件標簽個數(shù)

    在使用IDEA進行編程時,可能會同時打開多個文件,當文件過多時,文件標簽會占據(jù)大部分的IDEA界面,影響我們的編程效率,因此,我們可以通過設置IDEA的文件標簽顯示個數(shù),來優(yōu)化我們的編程環(huán)境,具體的設置方法如下
    2024-10-10
  • SpringBoot如何優(yōu)雅地使用Swagger2

    SpringBoot如何優(yōu)雅地使用Swagger2

    這篇文章主要介紹了SpringBoot如何優(yōu)雅地使用Swagger2,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-07-07
  • SpringCloud鏈路追蹤組件Sleuth配置方法解析

    SpringCloud鏈路追蹤組件Sleuth配置方法解析

    這篇文章主要介紹了SpringCloud鏈路追蹤組件Sleuth配置方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • SpringBoot基于Redis實現(xiàn)生成全局唯一ID的方法

    SpringBoot基于Redis實現(xiàn)生成全局唯一ID的方法

    在項目中生成全局唯一ID有很多好處,生成全局唯一ID有助于提高系統(tǒng)的可用性、數(shù)據(jù)的完整性和安全性,同時也方便數(shù)據(jù)的管理和分析,所以本文給大家介紹了SpringBoot基于Redis實現(xiàn)生成全局唯一ID的方法,文中有詳細的代碼講解,需要的朋友可以參考下
    2023-12-12
  • spring aop之鏈式調用的實現(xiàn)

    spring aop之鏈式調用的實現(xiàn)

    這篇文章主要介紹了spring aop之鏈式調用的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-02-02

最新評論

景德镇市| 江川县| 东山县| 淄博市| 当阳市| 桂林市| 贡觉县| 双柏县| 海丰县| 剑阁县| 会理县| 涟水县| 策勒县| 隆回县| 汾西县| 壤塘县| 丹阳市| 南郑县| 商丘市| 乌兰县| 来安县| 麻江县| 九江县| 萨迦县| 阿鲁科尔沁旗| 洛扎县| 曲水县| 微博| 藁城市| 焦作市| 宿松县| 梅州市| 双桥区| 陇西县| 东方市| 乳山市| 卢湾区| 阜宁县| 福海县| 新乡市| 巧家县|