請考慮以下代碼段。爲什麼使用Java引用變量的「+」運算符和文字串聯不會導致String interning?
CASE#1
public class HelloWorld {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "ab";
str2 = str2 + "c";
System.out.println("str1 :" + str1+ ", str2 :" + str2);
System.out.println(str1 == str2);
}
}
結果是
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
str1 :abc, str2 :abc
false
這裏,str1 == str2
結果出來是假的。但是,如果使用「+」運算符連接兩個文字。它爲您提供字符串常量池中字符串文字「abc」的地址。考慮下面的代碼片段
CASE#2
public class HelloWorld {
public static void main(String[] args) {
String str1 = "abc";
//String str2 = "ab";
str2 = "ab" + "c";
System.out.println("str1 :" + str1 + ", str2 :" + str2);
System.out.println(str1 == str2);
}
}
結果是
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
str1 :abc, str2 :abc
true
是否有人可以解釋爲什麼字符串中的實習案例#2是做,而不是在CASE#1?爲什麼我們在CASE#1中將'str1 == str2'設爲false,在CASE#2中爲true?
用'javap -v'檢查字節碼;你會明白爲什麼。 –
實習成本很高。默認情況下,您可能不希望將其用於非常量字符串(在第一種情況下,乍一看有一部分看起來可變 - 即沒有潛在的靜態代碼分析)。 – Thilo