Reputation:
When I clone an arraylist am I actually getting the data copied? The API says a shallow copy but I'm not sure what this means.
Upvotes: 0
Views: 122
Reputation: 16540
Shallow copy means only the references are copied into a new ArrayList. That is, the objects referenced in the new cloned ArrayList are the same objects in the original ArrayList.
It's the equivalent of doing something like:
// shallow copy
Object[] original = {new SomeObject(), new SomeObject(), new SomeObject()};
Object[] copy = new SomeObject[original.length];
for(int i = 0; i < original.length; ++i)
copy[i] = original[i];
Now, assume SomeObject has a variable "int x":
SomeObject obj1 = original[0];
SomeObject obj2 = copy[0];
obj1.setX(123456);
System.out.println("obj2.x " + obj2.getX());
You'll see:
obj2.x 123456
However, if you were to add a new SomeObject to original, it would not be in copy.
original.add(new SomeObject());
original.size(); //4
copy.size(); //3
Upvotes: 2
Reputation: 80176
A new ArrayList is created but the objects in the list still point to the old objects
Upvotes: 0
Reputation: 308743
It means that the a duplicate of the List is created, but the references the duplicated List stores point to the same objects on the heap that the original does.
Upvotes: 1
Reputation: 73484
That means it clones the list but the elements are not cloned.
To copy the data you need to iterate over the list and clone each item.
List<SomeObject> newList = new ArrayList<SomeObject>();
for(SomeObject o : list) {
newList.add(o.clone());
}
Upvotes: 0