JAVA 中 ArrayList<Arraylist> 的深拷贝

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22684800/
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-13 17:16:09  来源:igfitidea点击:

Deep copy of an ArrayList<Arraylist> in JAVA

javaarraylistdeep-copy

提问by msc87

I checked other answers but I could not find a proper answer to my question. I want to create a copy of my ArrayList<ArrayList>, since I need the original one somewhere else. I used the .clone()method in different ways:

我检查了其他答案,但找不到我的问题的正确答案。我想创建一个 my 的副本ArrayList<ArrayList>,因为我需要其他地方的原始副本。我.clone()以不同的方式使用了该方法:

public class WordChecker {

    private ArrayList<ArrayList> copyOfList = new ArrayList<ArrayList>();

    public WordChecker(ArrayList<ArrayList> list) {
        for (int i = 0; i < list.size(); i++)
            for (int j = 0; j < 7; j++)
                copyOfList = (ArrayList<ArrayList>) list.clone(); // without error
                // copyOfList = list.clone();cannot convert from Object to
                // ArrayList<ArrayList>
                // copyOfList = list.get(i).clone();cannot convert from Object to
                // ArrayList<ArrayList>
                // copyOfList = list.get(i).get(j).clone();
    }

but still my main ArrayListchanges as I work on its copy. Could anybody tell me how I should get a deep copy in this case?

ArrayList在我处理它的副本时,我的主要变化仍然存在。有人能告诉我在这种情况下我应该如何获得深层副本吗?

Answer:I put the copying mechanism in my class constructor:

答:我把复制机制放在我的类构造函数中:

private ArrayList<List> checkedTags = new ArrayList<List>();
public WordChecker(ArrayList<ArrayList> list)
  {
     for (ArrayList word: list) copyOfList.add((ArrayList) word.clone());

}

the only problem is that this is not applicable to copy from ArrayList which made me to go through a for loop use .get() method.I feel they are basically the same at the end.

唯一的问题是这不适用于从 ArrayList 复制,这使我不得不通过 for 循环使用 .get() 方法。我觉得它们最后基本相同。

采纳答案by sanbhat

You can simply use ArrayList(Collection c)constructor

您可以简单地使用ArrayList(Collection c)构造函数

public <T> ArrayList<ArrayList<T>> deepCopy(ArrayList<ArrayList<T>> source) {
    ArrayList<ArrayList<T>> dest = new ArrayList<ArrayList<T>>();
    for(ArrayList<T> innerList : source) {
        dest.add(new ArrayList<T>(innerList));
    }
    return dest;
}

Caution:As mentioned by @Tim B this does not deep copy the elements within ArrayList

注意:正如@Tim B 所提到的,这不会深度复制 ArrayList 中的元素