0

I want to clone list:

public List<List<Test>> a = new ArrayList<List<Test>>();
public List<List<Test>> b = new ArrayList<List<Test>>();

But if I do:

b = (ArrayList<List<Test>>)a.clone();

Occurs an error:

The method clone() is undefined for the type List<List<Test>>

Can you help me?

Piotrek
  • 10,919
  • 18
  • 73
  • 136
  • You must override clone() from Object. A related question is http://stackoverflow.com/questions/869033/how-do-i-copy-an-object-in-java. – Mihai8 Feb 03 '13 at 12:42

4 Answers4

1

java.util.List does not implement Cloneable, so the compiler cannot ensure that the concrete implementation you are using does. So, it won't allow you to write a code that calls a method that may not be there.

If you know the concrete implementation, you can cast it. V.g., if it is an ArrayList<List<Test>> (since ArrayList does implement Cloneable), then you do

  b = (List<List<Test>>) ((ArrayList<List<Test>>) a).clone();

If you do not, implement your own method.

Remember that the default clone makes shallow copies. That is, the object returned will be a new List<List<Test>>, but the inner List<Test> and Test will not get copied and you will get references to the original objects.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
1

The clone() is not available for the abstract list, only for ArrayList. However it will not work as you expect as it only returns a shallow copy. To make a deep copy, you need to clone in a loop:

   for (List<Test> item: a)
      b.add(new ArrayList(item);
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
0

Use the constructor or the addAll method:

new ArrayList<>(a);
//or
b.addAll(a);
tb-
  • 1,240
  • 7
  • 10
0

If you're using Java 8, you can create a new list using the same objects as the previous one simply using streams:

List<Double> secondList = firstList.stream().collect(Collectors.toList());

If you want a new list that doesn't share the same objects with the first one, you can do this (supposing your objects implements Cloneable):

If you're using Java 8, you can create a new list using the same objects as the previous one simply using streams:

List<Double> secondList = firstList.stream().collect(Collectors.toList());

If you want a new list that doesn't share the same objects with the first one, you can do this (supposing your objects implements Cloneable):

List<Double> secondList = firstList.stream().map(v -> v.clone()).collect(Collectors.toList());
jfcorugedo
  • 9,793
  • 8
  • 39
  • 47