记一个坑-list.addAll()后,修改新list的内容,旧list也会跟着改

问题代码:

java 复制代码
public static void main(String[] args) throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("a",1);
        List<Map<String,Object>> l1 = new ArrayList<>();
        l1.add(map);
        List<Map<String,Object>> l2 = new ArrayList<>();
        System.err.println("l1:" + new Gson().toJson(l1));
        System.err.println("l2:" + new Gson().toJson(l2));
        l2.addAll(l1);
        for (Map<String, Object> mapUtil : l2) {
            mapUtil.put("b",1);
        }
        System.err.println("l1:" + new Gson().toJson(l1));
        System.err.println("l2:" + new Gson().toJson(l2));
    }

打印:

java 复制代码
l1:[{"a":1}]
l2:[]
l1:[{"a":1,"b":1}]
l2:[{"a":1,"b":1}]

可以看到我明显改的是l2,l1怎么也变了呢,原因就在 addAll()

修改代码:

java 复制代码
public static void main(String[] args) throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("a",1);
        List<Map<String,Object>> l1 = new ArrayList<>();
        l1.add(map);
        List<Map<String,Object>> l2 = new ArrayList<>();
        System.err.println("l1:" + new Gson().toJson(l1));
        System.err.println("l2:" + new Gson().toJson(l2));
        l2 =(List<Map<String,Object>>) SerializationUtils.clone((Serializable) l1);
        for (Map<String, Object> mapUtil : l2) {
            mapUtil.put("b",1);
        }
        System.err.println("l1:" + new Gson().toJson(l1));
        System.err.println("l2:" + new Gson().toJson(l2));
    }

打印:

java 复制代码
l1:[{"a":1}]
l2:[]
l1:[{"a":1}]
l2:[{"a":1,"b":1}]

完美

相关推荐
hweiyu004 分钟前
Maven 私库
java·maven
Super Rookie12 分钟前
Spring Boot 企业项目技术选型
java·spring boot·后端
写不出来就跑路17 分钟前
Spring Security架构与实战全解析
java·spring·架构
ZeroNews内网穿透1 小时前
服装零售企业跨区域运营难题破解方案
java·大数据·运维·服务器·数据库·tcp/ip·零售
sleepcattt1 小时前
Spring中Bean的实例化(xml)
xml·java·spring
lzzy_lx_20891 小时前
Spring Boot登录认证实现学习心得:从皮肤信息系统项目中学到的经验
java·spring boot·后端
Dcs2 小时前
立即卸载这些插件,别让它们偷你的资产!
java
小七mod2 小时前
【Spring】Java SPI机制及Spring Boot使用实例
java·spring boot·spring·spi·双亲委派
亿.62 小时前
【Java安全】RMI基础
java·安全·ctf·rmi
ruan1145142 小时前
Java Lambda 类型推断详解:filter() 方法与 Predicate<? super T>
java·开发语言·spring·stream