equals()方法和「==」運算符

超類object中的比較

超類Object中有這個equals()方法,該方法主要用於比較兩個對象是否相等。該方法的源碼以下:java

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

equals()方法和「==」運算符比較

首先籠統的來說 「java中equals()方法和「==」運算符」 都是比較的地址,那爲何咱們在使用中總會出現混淆的狀況呢總是弄錯呢,這是由於「重寫equals()方法」和一些 「特殊狀況」的存在。this

對於字符串變量來講,使用「==」和「equals()」方法比較字符串時,其比較方法不一樣。

  • 「==」比較兩個變量自己的值,即兩個對象在內存中的首地址。
  • 「equals()」比較字符串中所包含的內容是否相同。
public class Tets {
    public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("abc");
        System.out.println(s1==s2);
        System.out.println(s1.equals(s2));
        StringBuffer s3 = new StringBuffer("abc");
        StringBuffer s4 = new StringBuffer("abc");
        System.out.println(s3==s4);
        System.out.println(s3.equals(s4));
    }
}

輸出結果code

false
true
false
false

按照全部類都是繼承超類object,超類object中的equals方法比較的是地址,爲何string類卻不是在比較地址呢,就是由於string類中發生了equals重寫。對象

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;
    }

在stringbuffer類中沒有對equals方法重寫,因此結果是false,請看stringbuffer中的equals方法。繼承

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

stringbuffer的比較咱們能夠獲取string對象之後再進行比較內存

s3.toString().equals(s4.toString());

對於非字符串變量來講,"=="和"equals"方法的做用是相同的都是用來比較其對象在堆內存的首地址,即用來比較兩個引用變量是否指向同一個對象。

public class Tets {
    public static void main(String[] args) {
        Tets tets = new Tets();
        Tets tetsb = new Tets();
        tets.equals(tetsb);
    }
}

equals文檔

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

注意

若是是基本類型比較,那麼只能用==來比較,不能用equals字符串

對於基本類型的包裝類型,好比Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用變量,==是比較地址的,而equals是比較內容的。get

public class Tets {
    public static void main(String[] args) {
        Integer n1 = new Integer(30);
        Integer n2 = new Integer(30);
        Integer n3 = new Integer(31);
        System.out.println(n1 == n2);//結果是false 兩個不一樣的Integer對象,故其地址不一樣,
        System.out.println(n1 == n3);//那麼無論是new Integer(30)仍是new Integer(31) 結果都顯示false
        System.out.println(n1.equals(n2));//結果是true 根據jdk文檔中的說明,n1與n2指向的對象中的內容是相等的,都是30,故equals比較後結果是true
        System.out.println(n1.equals(n3));//結果是false 因對象內容不同,一個是30一個是31
    }
}

參考 https://mp.weixin.qq.com/s/wH-SCnYqJBK5MPe7jOisTQ源碼

相關文章
相關標籤/搜索