Reputation: 448
Why is it, that when I add an object, to my ArrayList, which Should be passing it a Reference to the object, then I make the object equal to null, it outputs perfectly fine.
ArrayList<Test> testList = new ArrayList<>();
Test test = new Test();
System.out.println(test);
testList.add(test);
for(Test t : testList)
{
System.out.println(t);
}
test = null;
for(Test t : testList)
{
System.out.println(t);
}
The test constructor goes as:
int x = 0;
Test()
{
x = 50;
}
public String toString()
{
return x + "";
}
Yet, the output is 50, 50, 50 instead of 50, 50, null
Upvotes: 0
Views: 68
Reputation: 2588
Because there is a difference between Reference Types and Value Types in Java.
You add a reference to the value (a.k.a. an object) to the list, then you delete the reference. However the value is still there in memory, and the list still has a reference to that value, despite your original reference being nullified
Upvotes: 2
Reputation: 115328
When you are passing reference to object to ArrayList
you actually create yet another reference that is used by ArrayList to refer to the object.
When you assign null
to variable test
you actually "cancel" your reference. Nothing happens with reference of array list.
Even simpler.
If you have 2 variables: one and two:
Test one = new Test()
Test two = one;
At this point both references point to the same object.
one = null;
Now one
is null, but two
still refers to that object.
Upvotes: 1
Reputation: 178263
When you call add
, the ArrayList
now has its own reference to the same object.
test ----> Test() object
^
testList ----|
That is unaffected by setting your reference test
to null
.
test ----> null
testList ----> Test() object
Upvotes: 3