Interview question: Objects eligible for garbage collection

前端 未结 7 902
无人共我
无人共我 2020-12-02 19:03

Give the following code:

class A {
    Boolean b;
    A easyMethod(A a){
        a = null;
        return a;
    }
    public static void main(String [] args         


        
7条回答
  •  星月不相逢
    2020-12-02 19:40

    Assuming go is supposed to be easyMethod it works like this

    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 
        }
    }
    

    Two objects are eligible for garbage collection (a1 and a3). b is not because it's only a reference to null. No Boolean was ever made.

    To get around the inane subtleties of what // Some other code might be, I instead posit the question be reworded into the following:

    Prdict and explain the following output:

    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); }
        }
    }
    

    And output:

    c:\files\j>javac A.java
    
    c:\files\j>java A
    null
    2
    null
    

    And the followup is that at that point, a1 and a3 were eligible for GC, and a2 was not.

    The lesson from this question is that "Passing an object reference to a method and setting that reference to null does not cause the original reference to be nulled". That's the piece of knowledge the interviewer was attempting to test.

提交回复
热议问题