Reputation: 169
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?
Upvotes: 1
Views: 772
Reputation: 3537
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/
Upvotes: 0
Reputation: 8338
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.
Upvotes: 4
Reputation: 1421
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.
Upvotes: 1