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?
2 Answers
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.

- 698,415
- 94
- 811
- 1,216
-
1Note that a collection can contain itself, which is only possible with references: “[Some collection operations which perform recursive traversal of the collection may fail with an exception for self-referential instances where the collection directly or indirectly contains itself.](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Collection.html#:~:text=Some%20collection%20operations,contains%20itself.)” and that [mutable `Map` keys require special care](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html#:~:text=great%20care,in%20the%20map.) – Holger May 16 '22 at 10:23
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"?

- 104
- 6