In the Java collections (array, LinkedList, Set), when an object is added, does it saves a copy of the reference or copy the entire object to the collection. And if I change the original object does it effect the collection's object?
CodePudding user response:
In the java collections (Array , LinkedList , Set) when an object is added does it saves a copy of the reference or copy the entire object to the collection.
It saves a reference. It does not copy the object.
This can be inferred from the javadoc for the Collection.add
method:
boolean add(E e)
Ensures that this collection contains the specified element. Returns true if this collection changed as a result of the call.
Notice that it says that the collection will contain the specified element ... not a copy of the specified element.
If i change the original object does it effect the collection's object?
Yes. They are the same object.
CodePudding user response:
Yes, if you change the original object it does change the object inside the Collection.
You can read a similar question here which talks about java being a pass by reference: Is Java "pass-by-reference" or "pass-by-value"?