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);
相关推荐
caimouse4 分钟前
Reactos 第 5 章 进程与线程 — 5.2 Windows 进程的用户空间
windows·架构
莫逸风8 分钟前
【AgentScope】6.文件系统(Filesystem)详解
开发语言·windows·springai·agentscope·agnet
AIHR数智引擎33 分钟前
AI组织进化论:拆解微软、英伟达、Anthropic与Open AI如何重写组织
人工智能·经验分享·microsoft·职场和发展·aihr
超级无敌zhq35 分钟前
内网权限维持实战:打造持久化后门与隐蔽通道
网络·windows·安全·网络安全
shandianchengzi1 小时前
【记录】VSCode|Windows 下 VS Code 配置 Git Bash 为默认终端完整教程
windows·git·vscode·bash
caimouse1 小时前
Reactos 第 5 章 进程与线程 — 5.6 Windows 的进程创建和映像装入
windows
拂拉氏1 小时前
【项目分享-知识讲解】 C++标准库 list类的模拟实现
开发语言·c++·list·封装·stl标准库
泡^泡1 小时前
Python数据类型与运算符
开发语言·windows·python
caimouse13 小时前
Reactos 第 4 章 对象管理 — 4.5 几个常用的内核函数
c语言·windows·架构
caimouse14 小时前
Reactos 第 4 章 对象管理 — 4.3 句柄和句柄表(Handle & Handle Table)
c语言·windows·架构