詳解equals和==的區別

對於字符串變量:
1、如果使用的類重寫了equals()方法,那麼equals()比較的是字符串中包含的內容是否相同,否則equals()和==一樣比較的是內存地址;
2、==始終比較的是兩個變量的內存地址;

public class Test1 {
public static void main(String[] args) {
    String s1,s2,s3="abc",s4="abc";
    s1=new String("abc");
    s2=new String("abc");
    System.out.println(s1==s2);//false
    System.out.println(s3==s4);//true
     StringBuffer buf1 = new StringBuffer("a");
     StringBuffer buf2 = new StringBuffer("a");
     System.out.println(buf1.equals(buf2));//false,
     //因爲StringBUffer沒有重寫Object的equals()方法
}
}

對於非字符串變量:
“==”和”equals”方法的作用是相同的都是用來比較其
對象在堆內存的首地址,即用來比較兩個引用變量是否指向同一個對象。
另外:
1、 如果是基本類型比較,那麼只能用==來比較,不能用equals,否則編譯不能通過;

public class Test2 {
public static void main(String[] args) 
{
int a = 5;
int b = 4;
int c = 5;
System.out.println(a == b);//結果是false
System.out.println(a == c);//結果是true
System.out.println(a.equals(c));//錯誤,編譯不能通過
}
}

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

public class Test2 {
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
    System.out.println(n1.equals(n2));//true
}

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