public class J0 {
public static void main(String[] args) {
String str1 = new String("strOne");
String str2 = new String("strOne");
String str3 = "strTwo";
String str4 = "strTwo";
System.out.println(str1 == str2);
System.out.println(str3 == str4);
}
}
估計答案是什么?
是不是false,false ?
因為 String 類不能直接 "==" 號比較!new 出來的兩個String對象不在同一內(nèi)存。
應該用 "equals()"。
------------------------------------
可是答案是:false,true;
------------------------------------
怎么理解呢?
String str = new String("string");
?與 String str = "string";
聲明:以下解釋是保證正確的,我會從內(nèi)存空間上來解釋,比較清楚。
區(qū)別是,new String是在堆空間上分配一個空間,將指針指向這個空間,每一個new都是新的空間,==判斷當然是不等。
而String str = "ssss",說一下,在每種語言中對于字符串都有特殊的處理。
Java有一個專門的字符串池來保存可以重用的字符串。對于相同的字面值(也就是"雙引號里面你看到東西")相同,多少個變量他們都指向相同的空間,==判斷當然相等。
所以最正確的判斷字符串內(nèi)容相等的方法,就是用equals方法。String類這個immuable的類已經(jīng)覆蓋了這個從Object類繼承的eqauls方法,達到了對于內(nèi)容相等的判斷。
posted on 2007-01-05 09:19
壞男孩 閱讀(744)
評論(0) 編輯 收藏 所屬分類:
java命令學習