Why does the specified object be eligible for garbage collection?

For the record, I'm NOT a Java Beginner, but -- rather - an intermediate-level guy who kinda forgot a bit about fundamentals about Java.

class C{
    public static void main(String a[]){
        C c1=new C();
        C c2=m1(c1);        //line 4
        C c3=new C();
        c2=c3;              // line 6
        anothermethod();
    }
    static C m1(C ob1){
        ob1 =new C();      // line 10
        return ob1;
    }
    void anothermethod(){}
}

From the above code:

  • Why is it that after line 6, 2 objects of type C are eligible for Garbage Collection(GC)?

  • Why isn't it that in line 4 and line 10, a copy of c1 is passed into the m1() method. So, eventually in line 6, there is going to be 1 Object (not 2) that are going to be eligible for GC. After all, isn't java pass -by-value rather than pass-by-reference?


  • What makes you think two objects of type C are available for GC after line 6? I only see one ( c2 ). What tool are you using that tells you otherwise?

    Regarding your question about passing c1 into your m1 method: What you pass (by value) is a reference to the object -- a handle by which you can grab the object, if you will -- not a copy of it. The fact you pass a reference into m1 is completely irrelevant, in fact -- you never use that reference, you immediately overwrite it with a reference to a new object, which you then return (this does not affect the c1 that is still referenced in main ).


    There's a difference between pass-references-by-value and pass-values-by-reference :)

    Is Java Pass By Reference
    Java is never pass by reference right right
    Pass By Reference Or Pass By Value

    You might want to check out Jon Skeet's article on C# parameter-passing semantics as well, seeing as it's his favorite 'programmer ignorance' pet peeve:
    What's your favorite 'programmer ignorance' pet peeve.

    So basically, I see your code do the following:

    c1 = new C("Alice");
        // m1(C obj1) {     -- c1 gets passed to m1, a copy of the reference is made.
        //                  -- there are now two references to Alice (c1, obj1)
        //    obj1 = new C("Bob"); -- there is now one reference to Alice
                                    // and one reference to Bob
        //    return obj1;  -- returns a reference to Bob(c1 still reference Alice)
        // }                -- when m1 returns, one of the references to Alice disappears.
    c2 = m1(c1); // c2 points to Bob 
    c3 = new C("Charlie");
    c2 = c3;      // <-- Bob is eligible for collection. 
                  // There are now two references to Charlie
    
    链接地址: http://www.djcxy.com/p/20668.html

    上一篇: 改变Java中对象的地址(pass

    下一篇: 为什么指定的对象有资格进行垃圾回收?