首页 > 解决方案 > Java - 从旧列表创建新列表,旧列表也被修改

问题描述

我已经通过使用方法从旧列表创建了新列表addAll(),当我尝试修改新列表时,旧列表也被修改了。

例如 -

List<A> list = new ArrayList<A>();
        list.add(new A("something1"));
        list.add(new A("something2"));
        list.add(new A("something3"));
        list.add(new A("something4"));
        List<A> newList = new ArrayList<A>();
        newList.addAll(list);
        for(A a1 : newList){
            a1.setA("something new");
        }

        System.out.println("list----------------");
        for(A a1 : list){
            System.out.println(a1.toString());
        }
        System.out.println("new list----------------");
        for(A a1 : newList){
            System.out.println(a1.toString());
        }

输出 -

  list----------------
A [a=something new]
A [a=something new]
A [a=something new]
A [a=something new]
new list----------------
A [a=something new]
A [a=something new]
A [a=something new]
A [a=something new]

如何防止这种行为并保持旧列表不变?

标签: javaarraylistcollections

解决方案


Java 将对象的引用存储在列表中。因此,如果您制作一个副本列表,只有列表对象不同,它仍然使用对 A 对象的相同引用,换句话说,两个列表中都有相同的 A 对象。如果您想防止这种情况发生,您需要制作 A 对象的克隆副本。结果将如下所示:

List<A> newList = list.stream.map(a -> new A(a.getContent()).collect(Collectors.toList());

或者,如果您在 A 中有克隆/复制方法

List<A> newList = list.stream.map(A::clone).collect(Collectors.toList());

推荐阅读