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);
相关推荐
John Song2 小时前
ansible-playbook常用的检查命令
windows·ansible
视觉AI3 小时前
VS Code Remote-SSH 连接Jetson踩坑完整解决记录(网段不通+主机密钥变更双重故障)
运维·网络·人工智能·windows·ssh·边缘计算
观远数据10 小时前
从离线开发到实时同步:DataFlow如何支撑企业级数据治理闭环
java·windows·microsoft·excel
绀目澄清10 小时前
私服网游云加速程序劫持流量排查与修复总结
windows·安全
FL162386312910 小时前
Windows手动下载安装配置uv 0.11.29配置国内源含安装包和安装教程
windows·uv
Jelena1577958579211 小时前
淘宝商品详情API接口开发指南:应用市场选品比价实战
windows·microsoft
乖巧的妹子12 小时前
刷题总结知识
linux·服务器·windows
Leinwin12 小时前
技术视角深度对比:Google Gemini 与 Microsoft 365 Copilot 企业级 AI 办公架构解析
人工智能·microsoft·copilot
小李云雾12 小时前
LangGraph[2] ---- 控制流与持久化:让图“活”起来
windows·程序人生·ai·langgraph
取经蜗牛12 小时前
Windows 下强制腾讯通 RTX 仅使用有线网卡(静态路由法)
windows