1

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.

but why int[] list2 = list1.clone(); can work?

Alex K
  • 8,269
  • 9
  • 39
  • 57
高亮节
  • 169
  • 1
  • 1
  • 9

3 Answers3

4

ArrayList's clone() method does a shallow copy, which you can read about here.

Consider using a copy constructor instead, 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.

Alex K
  • 8,269
  • 9
  • 39
  • 57
1

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. You can find an article about deep clone here. Deep Clone It's a guide to build your own deep clone function.

Community
  • 1
  • 1
Toby D
  • 1,465
  • 1
  • 19
  • 31
0

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[])

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

Aify
  • 3,543
  • 3
  • 24
  • 43
  • thank you a lot, this explains the int[]. but from the website you give me, it says "If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object." .Does it mean list2 in ArrayList has the same reference as list1? but after I add "list2.add(3.5);", list1 doesn't change. – 高亮节 Jan 29 '15 at 02:41
  • The references in the object haven't changed though; the 1.0, 2.0, and 0.5 inside list1 are still the same object as the 3 of those inside list2; it just so happens to be that adding a new object to list2 won't add the same object to list1. If list 1 had a variable x = 2.0, then list 2 would also have x = 2.0, and if you changed x in either one of them, they would both change. – Aify Jan 29 '15 at 17:07