有關於==和equal()的區別,==很少說比較的是基本類型的值和引用類型的地址值;不少人應該是困惑equal(),這個其實equal()是Object中的默認方法。String只是繼承和重寫了Object中equal()方法,說白了:在Object中比較的是兩個對象的地址值,在String中比較的是兩個的字符串的內容這個在API裏都有體現。數組
以 T1spa
String s1 = new String("hello");對象
String s2 = new String("hello");繼承
System.out.println(s1 == s2); //false字符串
System.out.println(s1.equals(s2));//true變量
T2引用
String s3 = new String("hello");方法
String s4 = "hello";im
System.out.println(s3 == s4);//false註釋
System.out.println(s3.equals(s4));//true
T3
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);//true
System.out.println(s5.equals(s6));//true
爲了便於理解我用以T4做爲註釋
T4
String s = new String(「hello」);
String s = 「hello」;的區別?
第一句話造了兩個對象。(一個或者兩個)
第二句話造了一個對象。(也可能沒有)
而後這個也就有了一個關於拼接是否相等的問題
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);//false
System.out.println((s1+s2).equals(s3));//true
System.out.println("helloworld" == s1 + s2);//false
System.out.println("helloworld" == "hello" + "world"); // true
在這個裏面有一個細節:字符串常量相加和變量相加的區別:
變量拼接,先開空間,而後拼接
常量拼接,先拼接,找,存在,就不開空間了,不然就開空間存儲。
數組中的這個equals和==的問題
int arr1[]={1,2,3};
int arr2[]={1,2,3};
System.out.println(arr1.equals(arr2));//false這個並非重寫的方法
System.out.println(Arrays.equals(arr1,arr2));//true
System.out.println(arr1==arr2);//false