java:进行列表深度复制的最佳方法 [英] java: best way to do deep copy of list of lists

查看:1249
本文介绍了java:进行列表深度复制的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序来做List<List<Integer>>的深层复制,并且我这样做是这样的:

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.

推荐答案

这是一个好方法吗?

Is this a good way to do?

很好.

是否有可能摆脱内循环?

Is it possible to get rid of the inner loop?

是的,您可以使用ArrayList复制构造函数:

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.

上面的代码将缩短代码,并将其委派给System.arraycopy,这可能会在某种程度上提高性能.当您填充空的ArrayList时,它还避免了重复的调整大小/复制操作.但是,如果您确实需要深层复制,从根本上讲,没有办法避免复制列表/数组的O(n)时间复杂性.由于您不解释为什么,因此需要详细的副本,因此,我将一字不漏.

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.

这篇关于java:进行列表深度复制的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆