简体   繁体   English

如何正确使用clone()方法?

[英]how to use clone() method properly?

I know I can create an object this way 我知道我可以这样创建对象

int[] list1 = {1, 2}; 
int[] list2 = list1.clone();

and this normally works. 这通常有效。 But why doesn't this work properly: 但是为什么这不能正常工作:

ArrayList<Double> list1 = new ArrayList<Double>();
list1.add(1.0);
list1.add(2.0);
list1.add(0.5);
ArrayList<Double> list2 = list1.clone();

What I know is that this code is fine 我知道的是这段代码很好

ArrayList<Double> list2 = (ArrayList<Double>)list1.clone();

maybe because list1.clone() is doesn't return a reference type, so it needs (ArrayList) to make it return a reference type. 可能是因为list1.clone()不返回引用类型,所以它需要(ArrayList)使其返回引用类型。

but why int[] list2 = list1.clone(); 但是为什么要int[] list2 = list1.clone(); can work? 能行得通?

ArrayList 's clone() method does a shallow copy, which you can read about here . ArrayListclone()方法执行浅表复制,您可以在此处阅读。

Consider using a copy constructor instead, new ArrayList(listToCopy) . 考虑使用复制构造函数new ArrayList(listToCopy) Something like this: 像这样:

ArrayList<Double> list1 = new ArrayList<Double>();
list1.add(1.0);
list1.add(2.0);
list1.add(0.5);
ArrayList<Double> list2 = new ArrayList<Double>(list1);

As to why what you tried to do the first time didn't work, the clone() method returns an Object type, so you need to cast it to a ArrayList<Double> before you can initialize another ArrayList with it. 至于为什么第一次尝试不起作用, clone()方法返回一个Object类型,因此您需要将其ArrayList<Double>转换为ArrayList<Double>然后才能使用它初始化另一个ArrayList

You can refer to this post, there are some useful answers there. 您可以参考这篇文章,那里有一些有用的答案。 Deep copy, shallow copy, clone 深层复制,浅层复制,克隆

In short, clone() only copies an object at 1 level (meaning shallow copy) while deep copy could copy an object at more than 1 level. 简而言之,clone()仅复制1级的对象(表示浅复制),而深复制则可以复制1级以上的对象。 You can find an article about deep clone here. 您可以在此处找到有关深度克隆的文章。 Deep Clone It's a guide to build your own deep clone function. 深度克隆这是构建自己的深度克隆功能的指南。

In response to your new question, why does the int[] cloning work, it is because when clone() runs over an int[], all it sees are primitive types, and as such, simply returns the reference to the primitive type (which happens to be, you guessed it, an int[]) 为了回答您的新问题,为什么int []克隆起作用,这是因为,当clone()在int []上运行时,它看到的只是原始类型,因此,只需返回对原始类型的引用(您猜对了,这是一个int [])

see: http://howtodoinjava.com/2012/11/08/a-guide-to-object-cloning-in-java/ 参见: http : //howtodoinjava.com/2012/11/08/a-guide-to-object-cloning-in-java/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM