開始:"t" + "e"
是一個字符串文字,因爲它會被編譯器優化。這個字符串也被用在這一行:
String a = new String("te");
現在,String(String)
構造使得字符串的物理副本。所以,這意味着a
和d
是而不是相同的對象。
Then:String.equals(String)
比較兩個字符串。它說,如果內容是平等的,而不是對象。這意味着你可能有兩個不同的字符串對象,它們具有相同的字符序列,這將使String.equals(String)
返回true
。
String.intern()
將字符串放入字符串池中,如果它尚未在其中。但是這種方法不能改變對象本身。所以這個代碼示例將打印錯誤:
String literal = "lit";
String nonLiteral = "abclit".substring(3); // equals "lit"
nonLiteral.intern(); // "lit" was already in the String pool
// but `nonLiteral` is still `nonLiteral`
System.out.println(literal == nonLiteral); // false
但是,如果你這樣做:它會返回true:
String literal = "lit";
String nonLiteral = "abclit".substring(3); // equals "lit"
nonLiteral = nonLiteral.intern(); // "lit" was already in the String pool and
// it will return the object `literal`.
// Now the value is replaced.
System.out.println(literal == nonLiteral); // true
但 字符串A = 「TE」; String c =「t」+「e」; System.out.println(a == c); // true – 2011-12-17 23:21:10
Works也。所以沒有必要在池中實習字符串? – 2011-12-17 23:21:42
字符串文字被自動攔截,Java編譯器將「t」+「e」編譯爲「te」。 – 2011-12-17 23:24:37