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);
相关推荐
不总是2 小时前
Windows 系统 Node.js 免安装版(zip)安装与配置教程(2026 最新)
前端·windows·node.js
不总是5 小时前
[2026最新] Windows 免安装版 MySQL 8 详细安装配置教程(ZIP 压缩包版)
数据库·windows·mysql
2401_876964136 小时前
27考研余炳森概率论|喻老李良2027资料网课
windows·git·考研·svn·eclipse·github·概率论
介一安全6 小时前
【漏洞学习】PHP+Windows环境通用文件上传漏洞深度剖析
windows·web安全·php·文件上传·安全性测试
思麟呀6 小时前
C++工业级日志项目(六)异步日志器
linux·c++·windows
fastjson_7 小时前
Win11 关闭拖动窗口自动出现的贴靠窗口分栏
windows
早睡身体真不戳7 小时前
【无标题】
java·服务器·windows
不总是7 小时前
JDK17在Windows 系统 安装与环境变量配置
windows
fastjson_9 小时前
Windows11 无法删除文件,提示:你需要 SYSTEM 提供的权限才能对此文件进行更改
windows
Face10 小时前
WSL2 初始使用
linux·windows