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);
相关推荐
java资料站3 小时前
十一、Spring AI Alibaba · 高级 · 多智能体(Multi-agent)
人工智能·spring·microsoft
bug和崩溃我都要4 小时前
QT 开发的专业截图录屏工具 - macOS版 / Windows版
windows·qt·mac·录屏·截屏
kimloner4 小时前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)
windows·开源·c#·ocr·winforms
摸鱼 特供版5 小时前
一款边录边标注的轻量截图录屏工具
windows·学习·电脑·音视频·软件需求
夜雪一千5 小时前
Python 生成模拟地址数据:Faker之外的备选库
网络·windows·python
无忧.芙桃6 小时前
C++语言原理与实践(十二):list类的底层实现
c++·windows·list
Vex2une7 小时前
PowerShell ISE 到 VS Code 迁移史:从集成脚本环境到现代编辑器工作流
windows·vscode·powershell·powershell ise·powershell 扩展·powershell 7·脚本编辑器
空 白II7 小时前
10.10 大语言模型研究简报:Microsoft 发布 Windows 端侧混合智能架构
windows·microsoft·语言模型
大貔貅喝啤酒7 小时前
Windows 安装 使用JMeter 教程
windows·jmeter
报错小能手9 小时前
Channel面试题。Sync面试题
linux·服务器·windows