list复制出新的list后修改元素,也更改了旧的list?

例子

addAll()

java 复制代码
    @Test
    public void CopyListTest(){
        Student student = Student.builder().id(1).name("张三").age(23).classId(1).build();
        Student student2 = Student.builder().id(2).name("李四").age(22).classId(1).build();

        List<Student> students = new ArrayList<>();
        students.add(student);
        students.add(student2);
        System.out.println("旧的list");
        for (Student stu : students){
            System.out.println(stu);
        }
        List<Student> list2 = new ArrayList<>();
        list2.addAll(students);
        list2.stream().forEach(t->t.setClassId(2));
        System.out.println("新的list");
        for (Student stu : list2){
            System.out.println("班级id"+stu.getClassId());
        }
        System.out.println("旧的list");
        for (Student stu : students){
            System.out.println("班级id"+stu.getClassId());
        }
    }

旧的list的值被改变

直接用 newList = oldList 是引用传递,复制的是地址

改变oldList里的内容同样也会影响到newList

newList.addAll(oldList)是值传递

参考:http://t.csdnimg.cn/EGcYC

但 用allAll() 原来的值也被改变了

解决

使用深度复制

java 复制代码
  public static <T> List<T> deepCopy(List<T> sourceList) throws IOException, ClassNotFoundException{
        ByteArrayOutputStream bo= new ByteArrayOutputStream();
        ObjectOutputStream oos= new ObjectOutputStream(bo);
        oos.writeObject(sourceList);
        ByteArrayInputStream bi= new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream ois=new ObjectInputStream(bi);
        @SuppressWarnings("unchecked")
        List<T> dest = (List<T>)ois.readObject();
        return dest;
    }

所复制的元素如果是对象,需要实现序列化。

参考:http://t.csdnimg.cn/EGcYC

如果所复制的元素是字符

java 复制代码
    List<String> newList=new ArrayList<String>(oldList);
相关推荐
阿汤猫6669 小时前
基于OpenCode的Harness架构实战验收指南v3.0 (windows系统)
windows·prompt
阿汤猫66610 小时前
基于OpenCode的Harness架构实战v2.2(windows系统)
windows·prompt
xiaoshuaishuai812 小时前
C# AvaloniaUI 资源找不到报错
java·服务器·前端·windows·c#
思麟呀13 小时前
C++11并发编程:call_once一次性执行+atomic原子类型+CAS无锁编程+自旋锁
linux·开发语言·jvm·c++·windows
爱讲故事的13 小时前
操作系统第一讲复习:为什么学习操作系统,以及操作系统到底在做什么?
linux·开发语言·windows·学习·ubuntu·c#
韩曙亮17 小时前
【错误记录】flutter pub get 执行报错 ( 打开 Windows 开发者模式 )
windows·flutter
刘欣的博客17 小时前
LiteNetLib WinForm Demo
数据库·microsoft·c#
一个人旅程~17 小时前
如何让bootcamp-win10中的触摸板像macbook中一样丝滑原生效果?
windows·经验分享·macos·电脑
DisonTangor18 小时前
微软重磅开源 Lens: 重新思考基础文本到图像模型的训练效率
人工智能·microsoft·ai作画·开源·aigc
zyl8372119 小时前
Python 四大核心数据结构:列表、字典、元组、集合
数据结构·windows·python