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);
相关推荐
艺杯羹1 小时前
告别碎片化ToolCall:Model Context Protocol (MCP) 核心机理与私有数据总线落地实战
人工智能·microsoft·系统架构·大模型·mcp
Li Ming&10 小时前
Windows Server 2019 操作系统《保姆级安装教程》
windows·信息与通信
陈天伟教授12 小时前
Windows操作技巧 -03
windows
TechExplorer36514 小时前
Windows 隐藏导航窗格【主文件夹】、【图库】、【OneDrive】
windows·onedrive
我一定会有钱14 小时前
官网谷歌浏览器离线安装包一键下载
windows
易点云徐源17 小时前
(已解决)Foxmail打开后2分钟左右崩溃
windows·foxmail
其实防守也摸鱼17 小时前
每天一个知识点——RCE漏洞
运维·服务器·数据库·windows·安全·github·漏洞
江湖人称菠萝包18 小时前
【Windows】《深入浅出Windows API程序设计:核心编程篇》笔记-Chapter6-动态链接库
windows·笔记
2601_9623649720 小时前
重装系统后,Windows Hello 为什么要重新录入人脸?
windows·安全·电脑
水饺编程20 小时前
第5章,[Win32 章节] :在平面直角坐标系中描点
c语言·c++·windows·visual studio