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);
相关推荐
Nebula_g7 小时前
JavaSE加强:Stream流
java·开发语言·windows·stream·javase·流
在角落发呆10 小时前
软件配置备份方法:从手动到自动化的实践指南
windows·安全
鱼宵10 小时前
Spring AI 初体验:配好 yml 就能聊,ChatClient 四步链式调用
人工智能·spring·microsoft·大模型·springai·chatclient
lingchen190611 小时前
Win 11 系统语言栏悬浮于桌面上影响操作感受,怎么取消?
windows
by2099911 小时前
list:迭代器与资源管理实现的综合叙述(下)
数据结构·c++·笔记·list
梅孔立11 小时前
Windows PowerShell 升级 Pi-Coding-Agent + OpenCode,解决 OpenCode 二进制无效报错
windows
东木月14 小时前
Windows C 盘清理指南:安全删除临时文件、缓存与 Prefetch
c语言·windows·安全
水饺编程14 小时前
第1章,[Win32 章节]:Windows 的方方面面
c语言·c++·windows·visual studio
Experience-摆渡15 小时前
微软开源 NVX:Agent 微虚拟机沙盒的硬件级隔离拆解
microsoft
超级大福宝15 小时前
VS Code Remote-SSH 因 RemoteForward 端口冲突导致连接失败的排查与解决
运维·服务器·windows·vscode·ssh