假设应该是这样工作的go
easyMethod
class A {
Boolean b;
A easyMethod(A a){
a = null; // the reference to a2 was passed in, but is set to null
// a2 is not set to null - this copy of a reference is!
return a; // null is returned
}
public static void main(String [] args){
A a1 = new A(); // 1 obj
A a2 = new A(); // 2 obj
A a3 = new A(); // 3 obj
a3 = a1.go(a2); // a3 set to null and flagged for GC - see above for why
a1 = null; // so far, a1 and a3 have been set to null and flagged
// Some other code
}
}
两个对象符合垃圾回收条件(a1 和 a3)。 不是因为它只是对 null 的引用。从来没有制造过。b
Boolean
为了绕过可能是什么的无聊微妙之处,我反而假设这个问题应该改写成以下内容:// Some other code
Prdict 并解释以下输出:
class A {
int i;
A(int i) { this.i = i; }
public String toString() { return ""+i; }
A go(A a){
a = null; // the reference to a2 was passed in, but is set to null
// a2 is not set to null - this copy of a reference is!
return a; // null is returned
}
public static void main(String [] args){
A a1 = new A(1); // 1 obj
A a2 = new A(2); // 2 obj
A a3 = new A(3); // 3 obj
a3 = a1.go(a2); // a3 set to null and flagged for GC - see above for why
a1 = null; // so far, a1 and a3 have been set to null and flagged
test(a1);
test(a2);
test(a3);
}
static void test(A a) {
try { System.out.println(a); }
catch(Exception e) { System.out.println((String)null); }
}
}
和输出:
c:\files\j>javac A.java
c:\files\j>java A
null
2
null
后续情况是,在这一点上,a1和a3有资格获得GC,而a2则没有。
从这个问题中得到的教训是,“将对象引用传递给方法并将该引用设置为 null 不会导致原始引用为 null”。这就是面试官试图测试的知识。