When list.addAll(list2)
is called will objects in lists be copied to list? or just copy their references... did not find any explanation on javadoc...
No copy of the objects or their data are made; their references are simply added to the list object.
No, the objects will not be copied; references to the same objects will be added to the list.
-
But does the contract enforce this? I see that ArrayList implements addAll() with a shallow copy, but there is no specification in the doc. – zw324 Oct 28 '11 at 3:46
-
2@ZiyaoWei It states that it "appends all the elements", so that's what it will do--append all the elements. A copy of an element isn't the element, it's a copy. – Dave Newton Oct 28 '11 at 3:48
-
@ZiyaoWei: there's no general way to copy an object in Java: there are no automatically generated copy constructors as in C++, and the
clone()
method is supported by very few classes. Therefore, a container that wanted to copy all its elements would find itself unable to do so. – Ernest Friedman-Hill Oct 28 '11 at 4:34 -
So what will happen if we add an element later to the
list2
? Will it be added tolist
automatically? – iamprem Apr 25 '15 at 20:15 -
In general, java will not copy objects when you "add all", that is, for objects, pointers to the originals are used.
* But be careful ! For strings, due to immutability, an array copy will not point to the original string values, and you must not expect that changing a pointer to a string that was added to an array list will result in a new value inside the array list.