在 Java 中,给定一个列表 xs
,我们能否获得列表 ys
,以便为 ys
的第 n 个元素赋予一个新值。 xs
没有被修改。这是否可以在不必复制所有 xs
的情况下完成,将副本称为 ys
然后修改 ys
?
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> xs = new ArrayList<Integer>(100);
xs.add(10);
System.out.println(xs.get(0)); // prints 10
destructiveCall(xs);
System.out.println(xs.get(0)); // prints 5
List<Integer> ys = nonDestructiveUpdate(xs);
System.out.println(xs.get(0)); // prints 5 (the value has not changed)
System.out.println(ys.get(0)); // prints 20 (the value set in the nonDestructiveUpdate)
}
private static void destructiveCall(List<Integer> xs) {
xs.set(0, 5);
}
private static List<Integer> nonDestructiveUpdate(List<Integer> xs) {
List<Integer> ys = new ArrayList<Integer>(xs);
// is there a way of doing this without copying the whole list?
ys.set(0, 20);
return ys;
}
}
最佳答案
您可以编写自己的类,其中包含“基本列表”,在您的情况下为 xs
和另一个虚拟列表 - ys
,您可以在其中跟踪更改。您可以为您的 ys
虚拟列表创建方法和迭代器,因此它可以显示为真实列表,即使它不是。
但是在 Java 功能的标准库中我不知道这样的事情。
关于java - 在 Java 中有效地复制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977810/