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);
相关推荐
GlobalInfo3 小时前
2026年机器人多指灵巧手市场分析报告——涵盖行业调查、趋势分析与发展前景
大数据·人工智能·microsoft·微服务·机器人
zzu123zsw5 小时前
从臃肿的模板调用到声明式契约:深入 UniHttp 动态代理与多渠道生命周期扩展
java·spring boot·microsoft·unihttp
华普微HOPERF10 小时前
Matter协议架构详解:数据模型与交互模型深度解析
microsoft·架构·交互
?re?ta?rd?ed?11 小时前
C++11新特性,{}与左值
c++·windows
咸咸咸虾11 小时前
Microsoft Visual Studio 历史版本与官方安装包链接汇总
ide·microsoft·visual studio
必须得开心呀14 小时前
windows10系统任务栏图标消失修复
windows
zl_dfq14 小时前
Windows 下 UDP 套接字编程指南
网络·windows·udp
学习论之费曼学习法15 小时前
无人值守AI内容矩阵实战(10):Windows 上让 Python 进程 7×24 活着
人工智能·windows·python·矩阵·powershell·进程守护
少年的范儿16 小时前
Windows 安装 MySQL 8.4 教程(ZIP 解压版):配置 my.ini、初始化数据库与启动服务
数据库·windows·mysql
胖纸不争16 小时前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core