java: best way to do deep copy of list of lists

十年热恋 提交于 2020-08-26 13:45:22

问题


I am trying to write a procedure do the deep copy of List<List<Integer>>, and I am doing like this:

public static List<List<Integer>> clone(final List<List<Integer>> src)
{
    List<List<Integer>> dest = new ArrayList<List<Integer>>();
    for( List<Integer> sublist : src) {
        List<Integer> temp = new ArrayList<Integer>();
        for(Integer val: sublist) {
            temp.add(val);
        }
        dest.add(temp);
    }
    return dest ;
} 

Is this a good way to do? Is it possible to get rid of the inner loop? The fact is that each of the inner sub-lists can grow to large lengths.


回答1:


Is this a good way to do?

It's fine.

Is it possible to get rid of the inner loop?

Yes, you can use the ArrayList copy constructor:

for( List<Integer> sublist : src) {
    dest.add(new ArrayList<>(sublist));
}

The fact is that each of the inner sub-lists can grow to large lengths.

The above will shorten the code, and it delegates to System.arraycopy, which will likely improve performance somewhat. It also avoids the repeated resize/copy when you fill an empty ArrayList. But there's fundamentally no way to avoid the O(n) time complexity of copying a list/array, if you truly need a deep copy. Since you don't explain why you need a deep copy, I'll have to take you at your word.




回答2:


You might be able to speed things up with some parallel approach, like using a Thread pool to split the work at first and merge the results together after everything is done.

I can't provide an example since I'm on my phone, but may try to look that way.




回答3:


Try this.

public static <T> List<List<T>> clone(final List<List<T>> src) {
    return src.stream()
        .map(list -> list.stream().collect(Collectors.toList()))
        .collect(Collectors.toList());
} 


来源:https://stackoverflow.com/questions/44640648/java-best-way-to-do-deep-copy-of-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!