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);
相关推荐
the3clipse16 小时前
MPC-HC 下载安装与最佳配置教程:免费开源、轻量无广告、支持 4K 硬解的 Windows 播放器
windows·播放器·安装教程·硬件加速·mpc-hc·字幕设置·lav filters
独隅16 小时前
WebStorm Windows 版 React / Next.js 实战替换指南
javascript·windows·webstorm
陈工大模型17 小时前
2026年11月最新免费解压软件横评:7-Zip 、 Win解压缩名列前茅
windows·软件工程·7-zip·压缩软件
Liangwei Lin20 小时前
Exchange Server 2019 部署手册
microsoft
ms365copilot1 天前
Microsoft 365 Copilot跨工作资料整理
microsoft·copilot
中二骚年2 天前
Windows 安全中心 / 防火墙故障,calc和Microsoft Store,终端(管理员)无法正常打开。 原因 + 修复方案
windows·安全·microsoft
万联WANFLOW2 天前
CVE-2026-98432 等漏洞自查:AI 查出的 Linux、Windows 漏洞,运维怎么确认受不受影响
linux·运维·windows·网络安全
AlanAshley2 天前
Windows 中导致延迟的软硬件及协议比重
windows
yuezhilangniao2 天前
win10中文 以及 PowerShell 开发日常
windows·powershell
kk_net88992 天前
微软常用运行库合集免费下载安装教程(附运行库安装包)微软运行库安装图文教程
其他·microsoft