我有以下代码:
public class MyOjbect {
public Integer z = 111;
@Override
protected void finalize() throws Throwable {
System.out.println("invoking GC in MyOjbect");
super.finalize();
}
}
public class GC {
private MyOjbect o;
private void doSomethingElse(MyOjbect obj) {
o = obj;
}
@SuppressWarnings("unused")
public void doSomething() throws InterruptedException {
System.out.println("Start");
MyOjbect o = new MyOjbect();
doSomethingElse(o);
o = new MyOjbect();
doSomethingElse(null);
System.gc();
// System.out.println("checking "+o.z);
}
public static void main(String[] args) throws InterruptedException {
GC gc = new GC();
gc.doSomething();
}
}
我想知道为什么在执行该方法后变量GC
垃圾。甚至变量还不是空的。事实上,当我调试代码后 不是空的而是垃圾它。此外,如果我取消注释最后一行,GC 会打印变量,然后调用 GC。o
doSomethingElse
o
o
doSomethingElse
GC
o.z
更新:对于问为什么局部变量与字段相同的人。我刚刚从 SCJP 测试考试中复制了一个问题,因为它是