假设
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 pre }}有两个对象可以进行垃圾回收(a1和a3)。
b不是因为它只是对null的引用。没有
Boolean什么时候进行。
为了避免
// Some other pre可能出现的无聊的微妙之处,我提出将问题改写为以下内容:
预测并解释以下输出:
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:filesj>javac A.javac:filesj>java Anull2null
后续工作是,此时a1和a3符合GC资格,而a2不符合GC资格。
这个问题的教训是“将对象引用传递给方法并将该引用设置为null不会导致原始引用为空”。那就是面试官试图测试的知识。



