0

In the following code I added the ex1 object to the ArrayList. Then I made the ex1 object to null. But when I returned the object from the arraylist still it is pervious value not changed to null. Why is that? As i think all the reference variable refer to same object in the heap. So it should be null

List<Example> ex = new ArrayList<>();
    Stack<Example> st = new Stack<>();
    Example ex1 = new Example();
    ex1.age = 15;
    ex.add(ex1);
    st.push(ex1);
    ex1 = null;
    //System.out.println(ex1.age);
    System.out.println(ex.get(0).age);
    System.out.println(st.peek().age);

Ouput is 15

trincot
  • 317,000
  • 35
  • 244
  • 286
Isuru 26
  • 11
  • 4

2 Answers2

1

This behavior is described in the Java Language Specification.

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.

So when you call the add method, the reference is copied, and this copy is stored. Changing the original reference to point to null has no effect on the copied reference.

What you could do is to pass a copied reference to something like AtomicReference. So while all references you copy point to the same location of the AtomicReference, you could update where this reference points to.

peterulb
  • 2,869
  • 13
  • 20
1

You did not make the ex1 object to null. You overwrote the ex1 variable, which contained a reference to an object, with null. This way you deleted one of (at least two) references to the object. However, the other reference(s) were not removed, so the object was not deleted either.

CiaPan
  • 9,381
  • 2
  • 21
  • 35