java:深度复制列表列表的最佳方法 [英] java: best way to do deep copy of list of lists
问题描述
我正在尝试编写一个程序来执行 List
的深层复制,我正在这样做:>
public static List>克隆(最终列表<列表<整数>> src){列表<列表<整数>>dest = new ArrayList>();for(列表<整数>子列表:src){列表<整数>temp = new ArrayList();for(整数值:子列表){temp.add(val);}dest.add(temp);}返回目标;}
这是一个好方法吗?是否有可能摆脱内循环?事实是,每个内部子列表都可以增长到很大的长度.
这是一个好方法吗?
没关系.
<块引用>有没有可能去掉内循环?
是的,您可以使用 ArrayList
复制构造函数:
for( List sublist : src) {dest.add(new ArrayList<>(sublist));}
<块引用>
事实上,每个内部子列表都可以增长到很大的长度.
以上将缩短代码,并委托给System.arraycopy
,这可能会提高性能有点.它还可以避免在填充空 ArrayList
时重复调整大小/复制.但是,如果您确实需要深层复制,则从根本上无法避免复制列表/数组的 O(n) 时间复杂度.既然你没有解释为什么你需要一个深拷贝,我就不得不接受你的话.
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?
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.
这篇关于java:深度复制列表列表的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!