比較“==”和equals

Object的“==”和equals

“==”比較的是引用的地址值;

equals調用的也是“==”這個方法,源碼如下:

public boolean equals(Object obj) {
    return (this == obj);
}


所以,如果我們對三個對象o1、o2、o3做比較,結果如下:

Object o1 = new Object();
		Object o2 = new Object();
		Object o3 = o2;
		
		System.out.println(o1.equals(o2)); // false
		System.out.println(o1==o2); // false
		
		System.out.println(o3.equals(o2)); // true
		System.out.println(o3==o2); // true

String的“==”和equals

String繼承與Object,所以他的==和上面的結果一致,對比的也是對象的引用地址;

String重寫了equals方法,比較的是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;
    }
 
   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;
    }
所以對s1,s2,s3的比較有如下結果:

String s1 = new String("aaaaaaa");
		String s2 = new String("aaaaaaa");
		String s3 = s2;
		
		System.out.println(s1==s2); // false
		System.out.println(s1.equals(s2)); // true
		
		System.out.println(s3==s2); // true
		System.out.println(s3.equals(s2)); // true


結論

1、基本類型“==”比較的爲值比較,對象“==”比較的是對象引用地址的比較

2、Object.equals比較的爲對象引用地址比較,String.equals比較的爲引用的字符值;

3、基本類型對應的對象引用,和String一致,即equals比較的也是值比較。


補充知識:

1、hashCode()和(“==”、equals)沒關係,作用是:在爲對象進行散列的時候,作爲key值輸入,所以我們的對象的hashCode()儘量不要相同。

2、Object默認提供的實現是:在內存地址的基礎上通過特定算法得出的,保證了hash值的不同。


當我們看到hashCode的時候,難道不應該想到hashMap、hashSet等和hash有關的類嗎?還是就是重寫equals()和hashCode()d的話題。這些另起一片文章來說吧。


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