If we pass a reference variable to method and modify the object's state, the modifications are permanent (Please correct me if I am wrong). Consider the code:

 class CardBoard {
    Short story = 200;
    CardBoard go(CardBoard cb) {                        //....(1)
    cb = null;
    return cb;
    }
    public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);       //pass c2 into a method ....(2)
    c1 = null;
    // do Stuff
    } }

When in the above code, we say cb=null and return cb, shouldn't c2 (and also c3) now have null reference? (PS: The original question asks for the objects that are eligible for gc after "//do stuff". The answer is given to be 2, but I am having problem in understanding it.)

有帮助吗?

解决方案

No, because cb=null only replace the referencing target of 'cb' from the original instance to null, therefore c2 won't be affected.

When you just pass c2 into the function, the situation would be something like this:

  cb       c2 
  |         | 
------------------
|      object    |
------------------

once cb is set to null, it becomes

null--cb       c2 
               | 
  -------------------
  |      object     |
  -------------------

and you return cb and assign to c3, it essentially does c3 = null.

However, on the other hand, if you change the internal state of that object, then certainly the state of the object referred by all the references will be changed..

其他提示

Java is strictly pass by value.

CardBoard go(CardBoard cb) { // here cb has a *copy* of address c2 points to
  cb = null; // when you modify cb, c2 still points to the original location
  return cb; // returning null now
}

CardBoard c3 = c1.go(c2); // c3 becomes null because of explicit assignment
c1 = null; // same as c3

Much of your confusion comes from observing this

If we pass a reference variable to method and modify the object's state, the modifications are permanent.

which appears as pass by reference but in Java works as pass by value (of the reference).

The modifications persist because the copy (of the address) still points to the original object. So, all the methods fired (using the copy reference) still fire on the original object.

But, if you were to destroy this copied reference (by setting it to null) it won't affect the original object or any other references pointing to it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top