在 Java 中有效地复制数组

efficient copying of arrays in Java

在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;
    }
}

您可以编写自己的 class,其中包含 "base list",在您的情况下 xs 和另一个虚拟列表 - ys,您可以在其中跟踪更改。您可以为 ys 虚拟列表创建方法和迭代器,因此它可以显示为真实列表,即使它不是。

但是在标准库中 o Java 功能我不知道这样的事情。

不清楚您要完成什么。如果你想更新 ys 而不更新 xs,那么它们有不同的状态。如果您担心列表元素被克隆,它们不会。但是您可能确实希望复制引用,以便您可以非破坏性地操作它们。

如果您正在寻找 ys 来仅跟踪更改,那么@libik 有一个很好的建议,但是根据您需要支持的操作(如果只是更新,不会太难,但 inserts/deletes 会更难)。