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);
相关推荐
R.lin12 分钟前
windows MySQL解压版安装教程
windows·mysql·adb
常家壮1 小时前
Windows隐藏账号创建完全指南:技术原理与安全实践
windows·安全·渗透测试·后门·windows隐藏账号
真上帝的左手4 小时前
18. 操作系统-Windows-命令提示符
windows
GHL2842710906 小时前
文件重命名(C++源码)
前端·c++·windows
fred_kang7 小时前
win11上使用SecoClient登录报错出现的SV无法连接至服务器信息
windows
拓端研究室8 小时前
专题:2025年游戏市场洞察报告:市场规模、用户行为、投资趋势|附320+份报告PDF、数据、可视化模板汇总下载
大数据·人工智能·microsoft
丁劲犇9 小时前
Visual C++下使用Win32 API为Release模式导出崩溃堆栈
c++·windows·crash·dump·离线调试·vc·崩溃堆栈
半夏知半秋9 小时前
kibana介绍与部署(Windows详细版)
大数据·运维·windows·学习·搜索引擎·全文检索
spencer_tseng9 小时前
Insufficient permissions [windows]
windows·acrobat 9.0
浪潮IT馆9 小时前
win11安装Git
windows·git