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);
相关推荐
云服务器租用费用11 小时前
2026年腾讯云OpenClaw(Clawdbot)+Skills云上部署及Windows本地集成轻松入门
运维·服务器·数据库·windows·云计算·腾讯云
烛之武11 小时前
Python速通笔记
windows·python
牛奶咖啡1311 小时前
windows系统中安装配置命令行工具——psping
windows·psping·psping与ping对比·下载安装配置psping·psping的核心功能与用法·psping参数
2601_9611940212 小时前
2026六级词汇PDF下载|大学英语六级单词表+音频PDF
windows·git·eclipse·pdf·github
ID_1800790547314 小时前
小红书笔记评论 API 接口深度解析(带全套 JSON 示例・技术实战版)
java·开发语言·windows
xyz59915 小时前
Windows下Codex安装详细配置使用指南
windows
事变天下17 小时前
国产ECMO破局者汉诺医疗闯关科创板:以“中国心”与“中国肺”托起生命希望
大数据·人工智能·microsoft
蓝速科技17 小时前
蓝速科技实践分享:政企信创改造中三大国产芯片方案选型与统信UOS构建指南
科技·microsoft
TechExplorer36518 小时前
IDEA弹窗提示Microsoft Defender占用性能解决方案(Windows Defender添加目录排除)
microsoft·intellij idea·defender
We Just Keep growing18 小时前
【MySQL运维篇】——日志、主从复制、分库分表、读写分离
java·运维·数据库·windows·学习·mysql