Reputation: 6507
I have an object which I add to a List
using the method theList.add(theObj)
.
If I now make changes to this object theObj
, will these changes always be reflected in the object stored in the list?
If yes, does this mean that List
in java stores only references and not unique copies of the objects it is passed?
Upvotes: 1
Views: 429
Reputation: 25834
If yes, does this mean that List in java stores only references and not unique copies of the objects it is passed?
Well, it will make a copy if you're using primitives. And possibly strings.
Upvotes: 0
Reputation: 1500495
You don't store an object in the list. You store a reference in the list.
And yes, if you make a change to the object via any reference, that change will be visible however else you get to the same object.
The same is true for assignment, argument passing etc:
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = builder;
builder.append("foo");
System.out.println(builder2); // Prints foo
Here the values of builder
and builder2
are references to the same StringBuilder
object - so having appended a string to the data in the object via builder
, you can reach the same information via builder2
.
Upvotes: 11