如何在 Java 中克隆通用列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:43:13  来源:igfitidea点击:

How do I clone a generic List in Java?

javagenericsarraylistclone

提问by Bill the Lizard

I have an ArrayList<String>that I'd like to return a copy of. ArrayListhas a clone method which has the following signature:

我有一个ArrayList<String>我想退回一份副本。 ArrayList有一个克隆方法,它具有以下签名:

public Object clone()

After I call this method, how do I cast the returned Object back to ArrayList<String>?

调用此方法后,如何将返回的 Object 转换回ArrayList<String>

采纳答案by Vinko Vrsalovic

ArrayList newArrayList = (ArrayList) oldArrayList.clone();

回答by jodonnell

ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();

回答by Allain Lalonde

I find using addAll works fine.

我发现使用 addAll 工作正常。

ArrayList<String> copy = new ArrayList<String>();
copy.addAll(original);

parentheses are used rather than the generics syntax

使用括号而不是泛型语法

回答by pkaeding

This should also work:

这也应该有效:

ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()

回答by Aaron

I think this should do the trick using the Collections API:

我认为这应该使用 Collections API 来解决问题:

Note: the copy method runs in linear time.

注意:复制方法以线性时间运行。

//assume oldList exists and has data in it.
List<String> newList = new ArrayList<String>();
Collections.copy(newList, oldList);

回答by Tom Hawtin - tackline

Why would you want to clone? Creating a new list usually makes more sense.

你为什么要克隆?创建一个新列表通常更有意义。

List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);

Job done.

任务完成。

回答by Julien Chastang

Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.

请注意 Object.clone() 有一些主要问题,在大多数情况下不鼓励使用它。请参阅Joshua Bloch 的“ Effective Java”中的第 11 条以获得完整的答案。我相信您可以安全地在原始类型数组上使用 Object.clone(),但除此之外,您需要明智地正确使用和覆盖克隆。您最好定义一个复制构造函数或一个静态工厂方法,根据您的语义显式克隆对象。

回答by Juan Besa

Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.

克隆 ArrayList 时要非常小心。Java 中的克隆是肤浅的。这意味着它只会克隆 Arraylist 本身,而不是它的成员。因此,如果您有一个 ArrayList X1 并将其克隆到 X2 中,则 X2 中的任何更改也会在 X1 中体现,反之亦然。当您克隆时,您只会生成一个新的 ArrayList,其中包含指向原始元素中相同元素的指针。

回答by Petr

I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).

我不是java专业人士,但我有同样的问题,我试图通过这种方法解决。(假设 T 有一个复制构造函数)。

 public static <T extends Object> List<T> clone(List<T> list) {
      try {
           List<T> c = list.getClass().newInstance();
           for(T t: list) {
             T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
             c.add(copy);
           }
           return c;
      } catch(Exception e) {
           throw new RuntimeException("List cloning unsupported",e);
      }
}

回答by GeRmAn

This is the code I use for that:

这是我使用的代码:

ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);

Hope is usefull for you

希望对你有用