gpt4 book ai didi

java:进行列表列表深度复制的最佳方法

转载 作者:行者123 更新时间:2023-12-05 01:44:50 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来执行 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.

上面将缩短代码,它委托(delegate)给System.arraycopy,这很可能是improve performance somewhat。 .它还避免了在填充空的 ArrayList 时重复调整大小/复制。但是,如果您确实需要深度复制,则根本无法避免复制列表/数组的 O(n) 时间复杂度。由于您没有解释为什么您需要深拷贝,所以我不得不相信您的话。

关于java:进行列表列表深度复制的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com