Java ArrayList独立拷贝

Java ArrayList independent copy

我用下面的方法复制了一个列表,你可以看到输出结果,它们是独立的。我弄错了什么吗?还是他们真的独立?因为我在互联网上做了一些研究,它告诉我这个方法应该通过引用传递(哪个列表 'a' 和 'copy' 应该依赖)。

public static void main(String[] args) {
    ArrayList<String> a = new ArrayList<>(Arrays.asList("X", "X"));
    ArrayList<String> copy = new ArrayList<>(a);
    copy.set(0, "B");
    copy.remove(copy.size()-1);
    System.out.println(a);
    System.out.println(copy);
}

输出:

[X, X]
[B]

是的,此方法应该按引用传递(哪个列表 'a' 和 'copy' 应该依赖)。但是这两个操作并不能证明这一点。

copy.set(0, "B");
copy.remove(copy.size()-1);

看看下面的代码能不能帮助你理解:


    public static void main(String[] args) {
        Process process = new Process(1);
        Process process2 = new Process(2);
        ArrayList<Process> a = new ArrayList<>(Arrays.asList(process, process2));
        ArrayList<Process> copy = new ArrayList<>(a);
        copy.get(0).id = 10;

        // This proves that both ArrayLists maintain the same Process object at this point
        // output:
        // [Id:10, Id:2]
        // [Id:10, Id:2]
        System.out.println(a);
        System.out.println(copy);


        // copy.remove(copy.size() - 1) or copy.set(0, process3) doesn't affect another ArrayList
        Process process3 = new Process(3);
        process3.id = 100;
        copy.set(0, process3);
        copy.remove(copy.size() - 1);
        // output:
        // [Id:10, Id:2]
        // [Id:100]
        System.out.println(a);
        System.out.println(copy);

    }

    static class Process {
        public int id;

        public Process(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Id:" + id;
        }
    }

根据 documentation, the ArrayList 复制构造函数:

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

修改一个列表对另一个列表没有影响,您的代码证实了这一点。