Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a separated copy of an ArrayList? [duplicate]

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

like image 376
5YrsLaterDBA Avatar asked Aug 25 '09 18:08

5YrsLaterDBA


People also ask

How do you copy an ArrayList to another ArrayList?

In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another. where src is the source list object and dest is the destination list object.

Can you clone an ArrayList?

The Java ArrayList clone() method makes the shallow copy of an array list. Here, the shallow copy means it creates copy of arraylist object.

How do you make a shallow copy of a list in Java?

ArrayList clone() method is used to create a shallow copy of the list. In the new list, only object references are copied. If we change the object state inside the first ArrayList, then the changed object state will be reflected in the cloned ArrayList as well.


1 Answers

Yes that's correct - You need to implement clone() (or another suitable mechanism for copying your object, as clone() is considered "broken" by many programmers). Your clone() 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 ArrayList and populating it with references to the same objects, which is why changes to the object are visible from both Lists. With the clone approach your code would look like:

List<Foo> originalList = ...;  // Create new List with same capacity as original (for efficiency). List<Foo> copy = new ArrayList<Foo>(originalList.size());  for (Foo foo: originalList) {   copy.add((Foo)foo.clone()); } 

EDIT: To clarify, the above code is performing a deep copy of the original List whereby the new List contains references to copies of the original objects. This contrasts to calling ArrayList.clone(), which performs a shallow copy of the List. In this context a shallow copy creates a new List instance but containing references to the original objects.

like image 155
Adamski Avatar answered Sep 22 '22 08:09

Adamski