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.