0

リストのクローンを作成したい:

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

しかし、私がそうする場合:

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

エラーが発生します:

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

手伝って頂けますか?

4

4 に答える 4

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.

于 2013-02-03T12:41:38.780 に答える
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);
于 2013-02-03T12:42:32.120 に答える
0

Use the constructor or the addAll method:

new ArrayList<>(a);
//or
b.addAll(a);
于 2013-02-03T12:41:58.150 に答える
0

Java 8 を使用している場合は、ストリームを使用するだけで、以前のものと同じオブジェクトを使用して新しいリストを作成できます。

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

最初のリストと同じオブジェクトを共有しない新しいリストが必要な場合は、これを行うことができます (オブジェクトが を実装していると仮定しますCloneable):

Java 8 を使用している場合は、ストリームを使用するだけで、以前のものと同じオブジェクトを使用して新しいリストを作成できます。

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

最初のリストと同じオブジェクトを共有しない新しいリストが必要な場合は、これを行うことができます (オブジェクトが を実装していると仮定しますCloneable):

List<Double> secondList = firstList.stream().map(v -> v.clone()).collect(Collectors.toList());
于 2015-05-19T09:48:50.117 に答える