有人問我這樣一個問題:Java如何處理內存中的String對象?
String s = "abc"; // creates one String object and one
// reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects,
// and one reference variable*
基於上述細節多少String對象,多少參考變量之前,下面的代碼中的println語句創建?
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
我的回答是 這段代碼的結果是春冬春夏
有兩個引用變量,S1和S2。共有八個String對象 創建如下:「春天」,「夏天」(迷失),「春夏」,「秋天」(迷失),「春天 秋天」 (迷路),「冬天」(迷路),「春天的冬天」(此時「春天」丟失)。
八個字符串對象中只有兩個在此過程中不會丟失。
它是正確的嗎?
好東西知道:http://stackoverflow.com/questions/7663252/java-string-concat-in-stringbuilder-call/請注意,我對這個問題的回答是錯誤的... – Gevorg