根據我所讀到的,該程序唯一可能的輸出是"A"
或者沒有打印輸出。但是由於new MyString("A").concat("B");
語句創建了一個新的對象,字符串爲"AB"
,這個對象是不是也被垃圾收集,導致輸出"AB"
?爲什麼「A」或沒有輸出只有這個代碼可能的輸出,它也可能是「AB」?
class MyString {
private String str;
MyString(String str) { this.str = str; }
public void finalize() throws Throwable {
System.out.print(str);
super.finalize();
}
public void concat(String str2) {
this.str.concat(str2);
}
public static void main(String[] args) {
new MyString("A").concat("B");
System.gc();
}
}
好吧,因爲此.str.concat(str2)將在內存」AB「中創建一個單獨的字符串,而不是引用它的對象MyString中的str。但是如果我們有了這個語句this.str + = str2;那麼在finalize方法中打印「AB」的可能性會存在嗎? – user439526 2010-10-31 07:07:34
是的,那麼可能性存在 – 2010-10-31 07:08:49