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);
相关推荐
lpfasd12310 小时前
WinSW在Win7上失败真相-实测与修复
windows·nginx
万山寒11 小时前
windows使用WinSW注册服务
windows
白搞电子13 小时前
ESP32-S31 项目如何制作 Windows 一键烧录包:完整镜像、esptool 与数据边界
windows·stm32·单片机
apple_6926588514 小时前
Github开源免费 红果短剧 Windows 电脑桌面版:民间开发者做的第三方播放器,不用装模拟器了
windows
Vex2une14 小时前
Windows 系统还原发展史:从快照回滚到现代恢复生态
windows·系统还原·系统重置·卷影复制·系统保护·windows re·系统映像备份
Sand(ContextGate)14 小时前
Python Agent 测试实战:测试与评估,让 Agent 像传统软件一样可交付
前端·javascript·python·microsoft·ai
Hello_Pyhx14 小时前
挖兔硬盘精灵 WatuDisk:从首次检测到日常检查的使用指南
运维·windows·硬盘·维护
女神下凡15 小时前
Win10/WIN11自动更新怎么永久关闭?有效的Win10/WIN11强制更新关闭方法.
microsoft
seahahacsdn16 小时前
Windows系统添加VHD双系统
windows·vhd系统·vhd双系统
Hello_Pyhx21 小时前
iPhoneMirror:把 iPhone 接入 Windows,先分清投屏与反控
windows·ios·iphone