Possible Duplicate:
Java: how to clone ArrayList but also clone its items?
I have a sample program like the following:
ArrayList<Invoice> orginalInvoice = new ArrayList<Invoice>();
//add some items into it here
ArrayList<Invoice> copiedInvoice = new ArrayList<Invoice>();
copiedInvoice.addAll(orginalInvoice);
I thought I can modify items inside the copiedInvoice and it will not affect these items inside originalInoice. But I was wrong.
How can I make a separated copy / clone of an ArrayList?
Thanks
Yes that’s correct – You need to implement
clone()(or another suitable mechanism for copying your object, asclone()is considered “broken” by many programmers). Yourclone()method should perform a deep copy of all mutable fields within your object. That way, modifications to the cloned object will not affect the original.In your example code you’re creating a second
ArrayListand populating it with references to the same objects, which is why changes to the object are visible from bothLists. With the clone approach your code would look like:EDIT: To clarify, the above code is performing a deep copy of the original
Listwhereby the newListcontains references to copies of the original objects. This contrasts to callingArrayList.clone(), which performs ashallow copyof theList. In this context a shallow copy creates a newListinstance but containing references to the original objects.