爲什麼屬性值相同兩對象不能直接「 == 」

前言

終於結束了考試,能夠繼續團隊的學習了,繼續上週的那個問題,雖然問題解決了,可是本身不知道問題根源在哪,通過潘老師的講解,終於明白是啥問題了。git

示例

@Test
    void example() {
        Long A = 1234L;
        Long B = 1234L;
        System.out.println( A == B);
        System.out.println(A.equals(B));

        long a = 1234L;
        long b = 1234L;
        System.out.println( a == b);
    }

結果:github

false
true
true

Long類型的A B 是兩個對象,均爲1234L,按照我以前的想法,既然兩個對象的值同樣,那麼就相等,可是我卻忽略了對象的比較方式,普通變量經過值進行比較,對象是經過內存調用進行比較的。segmentfault

查看一下每一個對象的Hash值以及內存調用:ide

@Test
    void example() {
        Long A = 1234L;
        Long B = 1234L;
        System.out.println(A.hashCode());
        System.out.println(B.hashCode());
        System.out.println(System.identityHashCode(A));
        System.out.println(System.identityHashCode(B));
    }

結果:學習

1234
1234
507911745
1537772520

經過對打印出的每一個對象信息的值進行對比,咱們發現,兩個對象的HashCode的值是相等的,可是調用的內存地址是不相等的,這就意味着這就是兩個對象,再來看一個例子:spa

@Test
    void example() {
        Long A = 1234L;
        Long B = 1234L;
        Long C = A;
        System.out.println( A == B);
        System.out.println( A == C);
        System.out.println(A.equals(B));
        System.out.println(A.hashCode());
        System.out.println(B.hashCode());
        System.out.println(System.identityHashCode(A));
        System.out.println(System.identityHashCode(B));
        System.out.println(System.identityHashCode(C));
    }

結果:指針

false
true
true
1234
1234
1234
507911745
1537772520
507911745

經過以上結果咱們能夠發現,此時使用「 A == C「 進行相等的斷定,結果是true,由於他們的內存地址是相等的,這就相似於指針,內存地址指向同一地址,那就是同一個對象。code

equals()

爲什麼使用Spring 內置的equals()方法就能判別對象相等呢,看一下這個方法:對象

public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

重點在於longValue,因爲方法所在文件爲只讀文件,因此只能經過本身打印去比較值:blog

@Test
    void example() {
        Long A = 1234L;
        Long B = 1234L;
        Long C = A;
        System.out.println(A.longValue());
        System.out.println(B.longValue());
        System.out.println(C.longValue());
    }

結果:

1234
1234
1234

查詢了好多關於longValue()的資料,沒有查到他的機制,猜想是有相似於HashCode的屬性進行轉換而後進行比較。

總結

以前對於對象比較的機制是不瞭解的,在聽了老師的講解以後恍然大悟,在本身嘗試以後也瞭解了好多,在此感謝潘老師的指導,新的學期即將開始,但願早點進實驗室學習,還記得本身立下的Flag,通宵就結了。

某大佬的感慨:

qq_pic_merged_1598680626090.jpg
個人Flag:
qq_pic_merged_1598680666553.jpg

本文做者:河北工業大學夢雲智開發團隊 張文達

相關文章
相關標籤/搜索