【Java】程式碼解釋“==”與“.equals()”的區別
阿新 • • 發佈:2021-06-28
程式碼解釋“==”與“.equals()”的區別
我們先來看一道題:
public class test {
public static void main (String args[]){
String s1=new String("hello");
String s2=new String("hello");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}
執行結果:
false
true
為什麼“==”和“equals”不同?區別到底在哪裡?
請看下面的程式碼
public class ceshi { public static void main (String args[]) { int s1=1,s2=1; //定義賦值類整型 String a1="qwe",a2="qwe"; //定義賦值類字串型 String b1=new String("hello"); //定義引用類字串 String b2=new String("hello"); System.out.println("s1==s2 :"+(s1==s2)); //測試賦值類整型 System.out.println("a1==a2 :"+(a1==a2)); //測試賦值類字串型 System.out.println("b1==b2 :"+(b1==b2)); //測試引用類字串 // System.out.println(s1.equals(s2)); int作為基本型別,不是物件,不可以用equals哦~ System.out.println("a1.equals(a2) :"+a1.equals(a2)); System.out.println("b1.equals(b2) :"+b1.equals(b2)); } } /* 作者:禿頭少女劉小花 日期:2019.7.24 轉載請註明原作者。 */
顯而易見,對於基本資料型別,equals和沒有區別。
但是對於 引用型別 ,只能使用equals來比較兩者內容是否相同。如果在引用型別中,使用比較,那麼,比較的其實是兩者的引用地址是否相同。
作者:禿頭少女劉小花
日期:2019.7.24
轉載請註明原作者。