java:深度复制列表列表的最佳方式
java: best way to do deep copy of list of lists
我正在尝试编写一个程序来执行 List<List<Integer>>
的深层复制,我是这样做的:
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?
是的,你可以使用ArrayList
复制构造函数:
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
,这很可能 improve performance somewhat。当你填充一个空的 ArrayList
时,它也避免了重复的 resize/copy。但是,如果您确实需要深层复制,则根本无法避免复制 list/array 的 O(n) 时间复杂度。既然你没有解释为什么你需要一个深拷贝,我将不得不相信你的话。
您也许可以通过一些并行方法加快速度,例如首先使用线程池拆分工作,并在完成所有操作后将结果合并在一起。
我无法提供示例,因为我正在使用 phone,但可以试着这样看。
我正在尝试编写一个程序来执行 List<List<Integer>>
的深层复制,我是这样做的:
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?
是的,你可以使用ArrayList
复制构造函数:
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
,这很可能 improve performance somewhat。当你填充一个空的 ArrayList
时,它也避免了重复的 resize/copy。但是,如果您确实需要深层复制,则根本无法避免复制 list/array 的 O(n) 时间复杂度。既然你没有解释为什么你需要一个深拷贝,我将不得不相信你的话。
您也许可以通过一些并行方法加快速度,例如首先使用线程池拆分工作,并在完成所有操作后将结果合并在一起。
我无法提供示例,因为我正在使用 phone,但可以试着这样看。