Java List的两种copy方式

copy后的两个对象互不影响,可理解为深层拷贝

  1. 测试入口
    public static void main(String[] args) {
        TestDto a = new TestDto("a");
        TestDto b1 = new TestDto("b1");
        TestDto b = new TestDto("b", b1);
        List<TestDto> list = new ArrayList<>(Arrays.asList(a, b));

//        List<TestDto> listCopy = EntityHelper.copyByStream(list);
        List<TestDto> listCopy = EntityHelper.copyByJson(list, new TypeReference<List<TestDto>>() {
        });

//        listCopy.removeIf(x -> x.getName().equals("a"));
        for (TestDto demo : listCopy) {
            if (demo.getDtoList() != null) demo.getDtoList().removeIf(x -> x.getName().equals("b1"));
        }
        System.out.println(list);

        // 输出
        // [TestDto(name=a, dtoList=null), TestDto(name=b, dtoList=[TestDto(name=b1, dtoList=null)])]
    }

2.工具类

    /**
     * 流的形式copy【复制后两个对象独立】【T必须实现Serializable】
     */
    public static <T extends Serializable> List<T> copyByStream(Collection<T> src) {
        // 将对象写到流里
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(src);
            // 从流里读出来
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(bi);
            return new ArrayList<>((Collection<? extends T>) oi.readObject());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("copy utils: data copy error");
        }
    }

    /**
     * 转json的形式copy【复制后两个对象独立】
     */
    public static <T> T copyByJson(T src, TypeReference<T> type) {
    //  这里就是简单的ObjectMapping转换了一下
        String json = entityToJson(src);
        return jsonToEntity(json, type);
    }

3.实体类

@Data
public class TestDto implements Serializable {
    private String name;
    private List<TestDto> dtoList;

    public TestDto() {
    }

    public TestDto(String name) {
        this.name = name;
    }

    public TestDto(String name, TestDto... dtoList) {
        this.name = name;
        this.dtoList = new ArrayList<>(Arrays.asList(dtoList));
    }
}

实测可行,就是copyByJson没法根据泛型来定义TypeReference,这样可以省掉一个传参。然而不行,一直出现map转entity失败的报错,强迫症着实难受。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值