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);
相关推荐
kakakahahahaha35 分钟前
Windows Steam 游戏存档在哪里?定位和恢复排查流程
windows·其他·电脑·笔记本电脑·内容运营·软件需求
Xy-unu36 分钟前
Windows 开启外接显示器 HDR 后外接显示器无信号、无法扩展模式故障记录
windows
troy1283 小时前
Codex 安全盲区:代码漏洞生成实测
windows·python·ci/cd·pycharm·django·github·fastapi
其实防守也摸鱼3 小时前
常见安全架构中 Shiro 的认证确认机制解析
运维·服务器·数据库·windows·github
五_谷_丰_登6 小时前
windows批处理脚本(bat)问题解决方案大全——持续更新
windows·bat
YCOSA20256 小时前
迎双节 雨晨 Windows 11 IoT 企业版 LTSC 26H1 轻装 28000.2956
windows·物联网
csdn_aspnet8 小时前
Windows 如何隐藏 IIS Web 服务响应头中的 IIS Server 版本信息
windows·iis·url rewrite
AxureMost9 小时前
VideoProc Converter AI 视频转换/下载/超分辨率
windows
李小白杂货铺10 小时前
从 macOS 免密 SSH 到 Windows 10 完整配置指南
windows·win10·openssh·踩坑·ssh服务器·免密连接·安装和配置
线上放牧人19 小时前
Windows删除图标缓存
windows·python·pyqt