根据我所读到的,该程序唯一可能的输出是"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