开发者

What does cloning an ArrayList get me?

开发者 https://www.devze.com 2023-02-18 00:46 出处:网络
When I clone an arrayli开发者_开发技巧st am I actually getting the data copied? The API says a shallow copy but I\'m not sure what this means.Shallow copy means only the references are copied into a n

When I clone an arrayli开发者_开发技巧st am I actually getting the data copied? The API says a shallow copy but I'm not sure what this means.


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


That means that you get a new list but with the same data in it


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.


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());
}


A new ArrayList is created but the objects in the list still point to the old objects

0

精彩评论

暂无评论...
验证码 换一张
取 消