0

So my question is: why assigning at line_2 doesn't affect on the created "test"? Аlthough line-1 affects.

public class Test {
    List list;

    Test() {
        list = new ArrayList();
        someVoid(list);
    }

    void someVoid(List myList) {
        myList.add(0);            // line 1
        myList = null;            // line 2
    }

    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.list.size()); // output: 1    , line 3
    }
}
Dima A.
  • 3
  • 2

3 Answers3

2

You are assigning the null value to the reference, not to the object, and once you exit the method that reference is lost (swapped by the Garbage Collector).

deamonLucy
  • 205
  • 3
  • 9
1

Because object are passed as "pointer to that object", so you create a new pointer (in this case myList) that points to the same object, and therefore, you have:

myList -> actual list of object

and when you do myList = null, you are assigning null to the pointer:

myList -> 0x0 // null

but the list that it was pointing to, is not been effected

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
1

List is a reference type, so you are really being passed a reference to the List. You can call its methods, but assignment will only change where the reference points to, not the actual object.

Nailuj29
  • 750
  • 1
  • 10
  • 28