308

How can I clone an ArrayList and also clone its items in Java?

For example I have:

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....

And I would expect that objects in clonedList are not the same as in dogs list.

Lii
  • 11,553
  • 8
  • 64
  • 88
palig
  • 7,651
  • 6
  • 24
  • 18
  • It was already discussed in [Deep clone utility recomendation](http://stackoverflow.com/questions/665860/deep-clone-utility-recomendation) question – Swiety Apr 03 '09 at 22:12

21 Answers21

218

I, personally, would add a constructor to Dog:

class Dog
{
    public Dog()
    { ... } // Regular constructor

    public Dog(Dog dog) {
        // Copy all the fields of Dog.
    }
}

Then just iterate (as shown in Varkhan's answer):

public static List<Dog> cloneList(List<Dog> dogList) {
    List<Dog> clonedList = new ArrayList<Dog>(dogList.size());
    for (Dog dog : dogList) {
        clonedList.add(new Dog(dog));
    }
    return clonedList;
}

I find the advantage of this is you don't need to screw around with the broken Cloneable stuff in Java. It also matches the way that you copy Java collections.

Another option could be to write your own ICloneable interface and use that. That way you could write a generic method for cloning.

cdmckay
  • 31,832
  • 25
  • 83
  • 114
217

You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.

public static List<Dog> cloneList(List<Dog> list) {
    List<Dog> clone = new ArrayList<Dog>(list.size());
    for (Dog item : list) clone.add(item.clone());
    return clone;
}

For that to work, obviously, you will have to get your Dog class to implement the Cloneable interface and override the clone() method.

gudok
  • 4,029
  • 2
  • 20
  • 30
Varkhan
  • 16,601
  • 5
  • 31
  • 24
  • 24
    You can't do it generically, though. clone() is not part of the Cloneable interface. – Michael Myers Apr 03 '09 at 20:47
  • 15
    But clone() is protected in Object, so you can't access it. Try compiling that code. – Michael Myers Apr 03 '09 at 20:49
  • 6
    All classes extend Object, so they can override clone(). This is what Cloneable is for! – Stephan202 Apr 03 '09 at 20:50
  • 3
    This is a good answer. Cloneable is actually an interface. However, mmyers has a point, in that the clone() method is a protected method declared in the Object class. You would have to override this method in your Dog class, and do the manual copying of fields yourself. – Jose Apr 03 '09 at 20:50
  • @Jose: Yes, you could do this with a specific class that has overriden clone() to make it public. But you can't do it generically; that's my point. – Michael Myers Apr 03 '09 at 20:51
  • @mmyers My bad. Yes, I knew that the Cloneable iface was pretty f***ed up, but I hadn't realized to what extent. – Varkhan Apr 03 '09 at 20:51
  • Also, Cloneable is just a signature interface, like Serializable. Even if you overwrite the clone() method in the Object class, if your class does not implement Cloneable, then the javac compiler will throw an error. – Jose Apr 03 '09 at 20:51
  • @Jose: Well, technically, you don't *have* to call super.clone() in your clone() method, so you don't absolutely have to implement Cloneable. See why nobody likes Cloneable? :D – Michael Myers Apr 03 '09 at 20:53
  • The idea of the Cloneable interface is that of a ``contract'': a promise to sensibly implement clone(). It is true that Dog needs to override clone() and then implement the interface. – Stephan202 Apr 03 '09 at 20:53
  • @mmyers You're right. Generically this wont work, because the interface and the method not defined in the same space. Good point. – Jose Apr 03 '09 at 20:54
  • 3
    I say, create a factory or builder, or even just a static method, that will take an instance of Dog, and manually copy fields to a new instance, and return that new instance. – Jose Apr 03 '09 at 20:55
  • @JoseChavez Yes, that would be a better design pattern. However the OP mentions cloning, which may be an imposed requirement. – Varkhan Apr 03 '09 at 20:57
  • Should also point out that `clone()` does not call the constructor, which may cause some problems for certain classes. – cdmckay Feb 04 '13 at 14:57
  • A good practice would be to have a constructor on the Dog class which takes in exactly 1 parameter - a Dog object - and "clone" using that constructor. But yeah... nobody really likes cloneables :) – milosmns Apr 15 '16 at 12:57
  • 2
    I suggest to never use a function named as "clone". Always use a function that named as "deepClone" or "shallowClone". – hyyou2010 Oct 19 '17 at 03:21
154

All standard collections have copy constructors. Use them.

List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original); //This does a shallow copy

clone() was designed with several mistakes (see this question), so it's best to avoid it.

From Effective Java 2nd Edition, Item 11: Override clone judiciously

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

This book also describes the many advantages copy constructors have over Cloneable/clone.

  • They don't rely on a risk-prone extralinguistic object creation mechanism
  • They don't demand unenforceable adherence to thinly documented conventions
  • They don't conflict with the proper use of final fields
  • They don't throw unnecessary checked exceptions
  • They don't require casts.

Consider another benefit of using copy constructors: Suppose you have a HashSet s, and you want to copy it as a TreeSet. The clone method can’t offer this functionality, but it’s easy with a conversion constructor: new TreeSet(s).

Community
  • 1
  • 1
Rose Perrone
  • 61,572
  • 58
  • 208
  • 243
  • 106
    As much as I'm aware of, the copy constructors of the standard collections create a *shallow* copy, not a *deep* copy. The question asked here looks for a deep copy answer. – Abdull Nov 29 '12 at 17:30
  • 27
    this simply wrong, copy constuctors do a shallow copy - the whol epoint of te question – NimChimpsky Feb 13 '13 at 15:41
  • 2
    What's right about this answer is that if you are not mutating the objects in the list, adding or removing items doesn't remove them from both lists. It's not *as* shallow as simple assignment. – Noumenon Aug 15 '15 at 20:55
56

Java 8 provides a new way to call the copy constructor or clone method on the element dogs elegantly and compactly: Streams, lambdas and collectors.

Copy constructor:

List<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toList());

The expression Dog::new is called a method reference. It creates a function object which calls a constructor on Dog which takes another dog as argument.

Clone method [1]:

List<Dog> clonedDogs = dogs.stream().map(Dog::clone).collect(toList());

Getting an ArrayList as the result

Or, if you have to get an ArrayList back (in case you want to modify it later):

ArrayList<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toCollection(ArrayList::new));

Update the list in place

If you don't need to keep the original content of the dogs list you can instead use the replaceAll method and update the list in place:

dogs.replaceAll(Dog::new);

All examples assume import static java.util.stream.Collectors.*;.


Collector for ArrayLists

The collector from the last example can be made into a util method. Since this is such a common thing to do I personally like it to be short and pretty. Like this:

ArrayList<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toArrayList());

public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
    return Collectors.toCollection(ArrayList::new);
}

[1] Note on CloneNotSupportedException:

For this solution to work the clone method of Dog must not declare that it throws CloneNotSupportedException. The reason is that the argument to map is not allowed to throw any checked exceptions.

Like this:

    // Note: Method is public and returns Dog, not Object
    @Override
    public Dog clone() /* Note: No throws clause here */ { ...

This should not be a big problem however, since that is the best practice anyway. (Effectice Java for example gives this advice.)

Thanks to Gustavo for noting this.

Lii
  • 11,553
  • 8
  • 64
  • 88
  • Do you see any performance impact of doing this way where Dog(d) is copy constructor? `List clonedDogs = new ArrayList<>(); dogs.stream().parallel().forEach(d -> clonedDogs.add(new Dog(d)));` – SaurabhJinturkar Jul 28 '16 at 23:55
  • 1
    @SaurabhJinturkar: Your version is not thread-safe and should not be used with parallel streams. That is because the `parallel` call makes `clonedDogs.add` get called from multiple threads at the same time. The versions which uses `collect` are thread-safe. This is one of the advantages of the functional model of the stream library, the same code can be used for parallel streams. – Lii Jul 29 '16 at 15:36
  • 1
    @SaurabhJinturkar: Also, the collect operation is fast. It does pretty much the same thing as your version does, but also work for parallel streams. You could fix your version by using, for example, a concurrent queue instead of an array list, but I'm almost certain that would be much slower. – Lii Jul 29 '16 at 15:39
  • Whenever I try to use your solution I get an `Unhandled exception type CloneNotSupportedException` on `d.clone()`. Declaring the exception or catching it doesn't solve it. – Gustavo Aug 23 '16 at 14:25
  • @Gustavo: That is almost certainly because the object you are cloning, (`Dog` in this example) does not support cloning. Are you sure it implements the `Clonable` interface? – Lii Aug 23 '16 at 15:06
  • @Lii It does. Plus it overrides `clone()`. I had to change my `clone()` not to throw any exceptions. – Gustavo Aug 23 '16 at 15:16
  • @Gustavo: Ah, now I understand, I thought you got an exception at runtime but you got a compilation error. Yes, alas, it is very inconvenient to work with checked exceptions together with streams and lambdas. I believe it is okay in this case however, because I think the best practice when overriding `clone` is to do what you did and not declare the exception (since you don't plan on throwing it anyway). I'll add a note about that to the answer. Thanks! – Lii Aug 23 '16 at 15:31
  • @Lii As stream is functional in nature, meaning `an operation on a stream produces a result, but does not modify its source.`, to my understanding, we do not need to use map. So, we can directly use, `List clonedList = dogs.stream().collect(Collectors.toList());` [Oracle Doc](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html) – Yogen Rai Apr 17 '17 at 21:51
  • @YogenRai: No, this is not the case. Your line of code would give a shallow copy of the list; the result would be new list, but it would contain the same `Dog` objects. The "*source list*" would not be modified, but any future modification of the content dogs would modify the same dogs as in the source. This question is about creating *new dog objects* in a new list. This is what is called a *deep copy*. – Lii Apr 18 '17 at 08:32
  • @Lii Ya you are right :) I didn't notice that change in any of element in `dogs` and vice versa with cloned list will be reflected on both of them. And, as others pointed out, I think copy constructor would be the best option to create new copy. So, our lamda would be `List clonedList = dogs.stream().map(Dog::new).collect(Collectors.toList());` and I have copy constructor there in `Dog` class. But anyway, thanks – Yogen Rai Apr 18 '17 at 14:22
  • @YogenRai: You're right, it's better with a copy constructors. I'll add that to the answer. – Lii Apr 19 '17 at 10:57
  • For **Android developers**: this `stream` function is only available for API >= 24 – Behrouz.M May 12 '20 at 09:54
30

Basically there are three ways without iterating manually,

1 Using constructor

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);

2 Using addAll(Collection<? extends E> c)

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(dogs);

3 Using addAll(int index, Collection<? extends E> c) method with int parameter

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(0, dogs);

NB : The behavior of these operations will be undefined if the specified collection is modified while the operation is in progress.

Lii
  • 11,553
  • 8
  • 64
  • 88
javatar
  • 1,332
  • 1
  • 17
  • 24
  • 56
    please not that all of these 3 variants only create *shallow copies* of the lists – electrobabe Mar 15 '16 at 13:57
  • 9
    This is not A deep clone, those two lists retain the same objects, just copied the references only but the Dog objects, once you modified either list, the next list will have the same change. donno y so many upvotes. – Saorikido Oct 12 '16 at 01:55
  • 2
    @Neeson.Z All methods create a deep copy of the list and a shallow copies of the element of the list. If you modify an element of the list the change will be reflected by the other list, but if you modify one of the list (for example removing an object), the other list will be unchanged. – Alessandro Teruzzi Jun 07 '18 at 15:08
17

I think the current green answer is bad , why you might ask?

  • It can require to add a lot of code
  • It requires you to list all Lists to be copied and do this

The way serialization is also bad imo, you might have to add Serializable all over the place.

So what is the solution:

Java Deep-Cloning library The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.

Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);

Check it out at https://github.com/kostaskougios/cloning

alexdriedger
  • 2,884
  • 2
  • 23
  • 30
Cojones
  • 1,906
  • 22
  • 25
  • 8
    One caveat with this method is that it uses reflection, which can be quite a bit slower than Varkhan's solution. – cdmckay Jun 21 '10 at 06:24
  • 6
    I dont understand the first point "it requires a lot of code". The library you're talking about would need more code. Its only a matter of where you place it. Otherwise I agree a special library for this kind of thing helps.. – nawfal Aug 07 '13 at 10:41
13

You can use JSON (with a JSON Library) to serialize and then unserialize the list. The serialized list holds no reference to the original object when unserialized.

Using Google GSON:

List<CategoryModel> originalList = new ArrayList<>(); // add some items later
String listAsJson = gson.toJson(originalList);
List<CategoryModel> newList = new Gson().fromJson(listAsJson, new TypeToken<List<CategoryModel>>() {}.getType());

You can also do it using other JSON libraries like Jackson.

The advantage of using this approach is that you can solve the problem without having to create classes, interfaces, and cloning logic (which can be very long if your object has other lists of objects inside)

Renato Probst
  • 5,914
  • 2
  • 42
  • 45
  • 1
    I don't know why people have downvoted this answer. Other answers have to implement clone() or have to change their dependencies to include new libraries. But JSon library most of projects would have already included. I upvoted for this. – Satish Mar 22 '18 at 18:13
  • 1
    @Satish Yes, this is the only answer which helped me, I'm not sure what's wrong with others, but no matter what I did, clone or use copy constructor, my original list used to get updated, but this way it does not, so thanks to the author! – Parag Pawar Dec 19 '18 at 15:29
  • 1
    Well, it's true that is not a pure Java reply for the knowledge´s sake but an efficient solution to deal with this issue quickly – marcRDZ Aug 07 '19 at 07:24
  • 1
    great hack , saves allot of time – m.yuki Feb 22 '20 at 23:47
5

I have used this option always:

ArrayList<Dog> clonedList = new ArrayList<Dog>(name_of_arraylist_that_you_need_to_Clone);
besartm
  • 558
  • 1
  • 7
  • 14
2
List<Dog> dogs;
List<Dog> copiedDogs = dogs.stream().map(dog -> SerializationUtils.clone(dog)).Collectors.toList());

This will deep copy each dog

Siavash Rostami
  • 1,883
  • 4
  • 17
  • 31
Raju K
  • 21
  • 1
2

Some other alternatives for copying ArrayList as a Deep Copy

Alernative 1 - Use of external package commons-lang3, method SerializationUtils.clone():

SerializationUtils.clone()

Let's say we have a class dog where the fields of the class are mutable and at least one field is an object of type String and mutable - not a primitive data type (otherwise shallow copy would be enough).

Example of shallow copy:

List<Dog> dogs = getDogs(); // We assume it returns a list of Dogs
List<Dog> clonedDogs = new ArrayList<>(dogs);

Now back to deep copy of dogs.

The Dog class does only have mutable fields.

Dog class:

public class Dog implements Serializable {
    private String name;
    private int age;

    public Dog() {
        // Class with only mutable fields!
        this.name = "NO_NAME";
        this.age = -1;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Note that the class Dog implements Serializable! This makes it possible to utilize method "SerializationUtils.clone(dog)"

Read the comments in the main method to understand the outcome. It shows that we have successfully made a deep copy of ArrayList(). See below "SerializationUtils.clone(dog)" in context:

public static void main(String[] args) {
    Dog dog1 = new Dog();
    dog1.setName("Buddy");
    dog1.setAge(1);

    Dog dog2 = new Dog();
    dog2.setName("Milo");
    dog2.setAge(2);

    List<Dog> dogs = new ArrayList<>(Arrays.asList(dog1,dog2));

    // Output: 'List dogs: [Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]'
    System.out.println("List dogs: " + dogs);

    // Let's clone and make a deep copy of the dogs' ArrayList with external package commons-lang3:
    List<Dog> clonedDogs = dogs.stream().map(dog -> SerializationUtils.clone(dog)).collect(Collectors.toList());
    // Output: 'Now list dogs are deep copied into list clonedDogs.'
    System.out.println("Now list dogs are deep copied into list clonedDogs.");

    // A change on dog1 or dog2 can not impact a deep copy.
    // Let's make a change on dog1 and dog2, and test this
    // statement.
    dog1.setName("Bella");
    dog1.setAge(3);
    dog2.setName("Molly");
    dog2.setAge(4);

    // The change is made on list dogs!
    // Output: 'List dogs after change: [Dog{name='Bella', age=3}, Dog{name='Molly', age=4}]'
    System.out.println("List dogs after change: " + dogs);

    // There is no impact on list clonedDogs's inner objects after the deep copy.
    // The deep copy of list clonedDogs was successful!
    // If clonedDogs would be a shallow copy we would see the change on the field
    // "private String name", the change made in list dogs, when setting the names
    // Bella and Molly.
    // Output clonedDogs:
    // 'After change in list dogs, no impact/change in list clonedDogs:\n'
    // '[Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]\n'
    System.out.println("After change in list dogs, no impact/change in list clonedDogs: \n" + clonedDogs);
}

Output:

List dogs: [Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]
Now list dogs are deep copied into list clonedDogs.
List dogs after change: [Dog{name='Bella', age=3}, Dog{name='Molly', age=4}]
After change in list dogs, no impact/change in list clonedDogs:
[Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]

Comment: Since there is no impact/change on list clonedDogs after changing list dogs, then deep copy of ArrayList is successful!

Alernative 2 - Use of no external packages:

A new method "clone()" is introduced in the Dog class and "implements Serializable" is removed compare to alternative 1.

clone()

Dog class:

public class Dog {
    private String name;
    private int age;

    public Dog() {
        // Class with only mutable fields!
        this.name = "NO_NAME";
        this.age = -1;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    /**
     * Returns a deep copy of the Dog
     * @return new instance of {@link Dog}
     */
    public Dog clone() {
        Dog newDog = new Dog();
        newDog.setName(this.name);
        newDog.setAge(this.age);
        return newDog;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Read the comments in the main method below to understand the outcome. It shows that we have successfully made a deep copy of ArrayList(). See below "clone()" method in context:

public static void main(String[] args) {
    Dog dog1 = new Dog();
    dog1.setName("Buddy");
    dog1.setAge(1);

    Dog dog2 = new Dog();
    dog2.setName("Milo");
    dog2.setAge(2);

    List<Dog> dogs = new ArrayList<>(Arrays.asList(dog1,dog2));

    // Output: 'List dogs: [Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]'
    System.out.println("List dogs: " + dogs);

    // Let's clone and make a deep copy of the dogs' ArrayList:
    List<Dog> clonedDogs = dogs.stream().map(dog -> dog.clone()).collect(Collectors.toList());
    // Output: 'Now list dogs are deep copied into list clonedDogs.'
    System.out.println("Now list dogs are deep copied into list clonedDogs.");

    // A change on dog1 or dog2 can not impact a deep copy.
    // Let's make a change on dog1 and dog2, and test this
    // statement.
    dog1.setName("Bella");
    dog1.setAge(3);
    dog2.setName("Molly");
    dog2.setAge(4);

    // The change is made on list dogs!
    // Output: 'List dogs after change: [Dog{name='Bella', age=3}, Dog{name='Molly', age=4}]'
    System.out.println("List dogs after change: " + dogs);

    // There is no impact on list clonedDogs's inner objects after the deep copy.
    // The deep copy of list clonedDogs was successful!
    // If clonedDogs would be a shallow copy we would see the change on the field
    // "private String name", the change made in list dogs, when setting the names
    // Bella and Molly.
    // Output clonedDogs:
    // 'After change in list dogs, no impact/change in list clonedDogs:\n'
    // '[Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]\n'
    System.out.println("After change in list dogs, no impact/change in list clonedDogs: \n" + clonedDogs);
}

Output:

List dogs: [Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]
Now list dogs are deep copied into list clonedDogs.
List dogs after change: [Dog{name='Bella', age=3}, Dog{name='Molly', age=4}]
After change in list dogs, no impact/change in list clonedDogs:
[Dog{name='Buddy', age=1}, Dog{name='Milo', age=2}]

Comment: Since there is no impact/change on list clonedDogs after changing list dogs, then deep copy of ArrayList is successful!

Note1: Alternative 1 is much slower than Alternative 2, but easier to mainatain since you do not need to upadate any methods like clone().

Note2: For alternative 1 the following maven dependency was used for method "SerializationUtils.clone()":

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Find more releases of common-lang3 at:

https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

DigitShifter
  • 801
  • 5
  • 12
2

You will need to clone the ArrayList by hand (by iterating over it and copying each element to a new ArrayList), because clone() will not do it for you. Reason for this is that the objects contained in the ArrayList may not implement Clonable themselves.

Edit: ... and that is exactly what Varkhan's code does.

Lii
  • 11,553
  • 8
  • 64
  • 88
Stephan202
  • 59,965
  • 13
  • 127
  • 133
  • 1
    And even if they do, there's no way to access clone() other than reflection, and it's not guaranteed to succeed anyway. – Michael Myers Apr 03 '09 at 20:48
1

for you objects override clone() method

class You_class {

    int a;

    @Override
    public You_class clone() {
        You_class you_class = new You_class();
        you_class.a = this.a;
        return you_class;
    }
}

and call .clone() for Vector obj or ArraiList obj....

RN3KK Nick
  • 701
  • 6
  • 12
1

A nasty way is to do it with reflection. Something like this worked for me.

public static <T extends Cloneable> List<T> deepCloneList(List<T> original) {
    if (original == null || original.size() < 1) {
        return new ArrayList<>();
    }

    try {
        int originalSize = original.size();
        Method cloneMethod = original.get(0).getClass().getDeclaredMethod("clone");
        List<T> clonedList = new ArrayList<>();

        // noinspection ForLoopReplaceableByForEach
        for (int i = 0; i < originalSize; i++) {
            // noinspection unchecked
            clonedList.add((T) cloneMethod.invoke(original.get(i)));
        }
        return clonedList;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        System.err.println("Couldn't clone list due to " + e.getMessage());
        return new ArrayList<>();
    }
}
milosmns
  • 3,595
  • 4
  • 36
  • 48
  • Neat and nasty trick! One potential problem: If `original` contains objects of different classes I think `cloneMethod.invoke` will fail with an exception when it is invoked with the wrong kind of object. Because of this it might be better to retrieve a specific clone `Method` for each object. Or use the clone method on `Object` (but since that one is protected that might fail in more cases). – Lii Aug 24 '16 at 07:44
  • Also, I think it would be better to throw a runtime exception in the catch-clause instead of returning an empty list. – Lii Aug 24 '16 at 07:46
0

Easy way by using commons-lang-2.3.jar that library of java to clone list

link download commons-lang-2.3.jar

How to use

oldList.........
List<YourObject> newList = new ArrayList<YourObject>();
foreach(YourObject obj : oldList){
   newList.add((YourObject)SerializationUtils.clone(obj));
}

I hope this one can helpful.

:D

sonida
  • 4,411
  • 1
  • 38
  • 40
  • 1
    Just a note: why such an old version of Commons Lang? See the release history here: http://commons.apache.org/proper/commons-lang/release-history.html – informatik01 Apr 30 '13 at 21:59
0

The package import org.apache.commons.lang.SerializationUtils;

There is a method SerializationUtils.clone(Object);

Example

this.myObjectCloned = SerializationUtils.clone(this.object);
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
pacheco
  • 1,637
  • 1
  • 10
  • 2
  • it's a little bit outdated to answer this question. And many other answers in the comment down under the question. – moskito-x May 02 '13 at 19:49
0

I have just developed a lib that is able to clone an entity object and a java.util.List object. Just download the jar in https://drive.google.com/open?id=0B69Sui5ah93EUTloSktFUkctN0U and use the static method cloneListObject(List list). This method not only clones the List but also all entity elements.

0

The below worked for me..

in Dog.java

public Class Dog{

private String a,b;

public Dog(){} //no args constructor

public Dog(Dog d){ // copy constructor
   this.a=d.a;
   this.b=d.b;
}

}

 -------------------------

 private List<Dog> createCopy(List<Dog> dogs) {
 List<Dog> newDogsList= new ArrayList<>();
 if (CollectionUtils.isNotEmpty(dogs)) {
 dogs.stream().forEach(dog-> newDogsList.add((Dog) SerializationUtils.clone(dog)));
 }
 return newDogsList;
 }

Here the new list which got created from createCopy method is created through SerializationUtils.clone(). So any change made to new list will not affect original list

gayu312
  • 61
  • 2
  • 7
0

Simple way is

ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);
Thanga
  • 7,811
  • 3
  • 19
  • 38
0

The other posters are correct: you need to iterate the list and copy into a new list.

However... If the objects in the list are immutable - you don't need to clone them. If your object has a complex object graph - they will need to be immutable as well.

The other benefit of immutability is that they are threadsafe as well.

Fortyrunner
  • 12,702
  • 4
  • 31
  • 54
0

Here is a solution using a generic template type:

public static <T> List<T> copyList(List<T> source) {
    List<T> dest = new ArrayList<T>();
    for (T item : source) { dest.add(item); }
    return dest;
}
-2

I think I found a really easy way to make a deep copy ArrayList. Assuming you want to copy a String ArrayList arrayA.

ArrayList<String>arrayB = new ArrayList<String>();
arrayB.addAll(arrayA);

Let me know if it doesn't work for you.

demongolem
  • 9,474
  • 36
  • 90
  • 105
jordanrh
  • 35
  • 3