list 浅,深拷贝

list 浅,深拷贝

参考: https://www.cnblogs.com/luxd/p/11933686.html


    //浅拷贝
    public void simpleTest1() {
        List<TestA> list = new ArrayList<>();
        list.add(new TestA("aa"));

        //浅拷贝
        TestA testA = new ArrayList<>(list).get(0);
        testA.setName("bb");
        System.out.println(list.get(0));

        List<TestA> objects = new ArrayList<>();
        objects.addAll(list);
        objects.get(0).setName("cc");
        System.out.println(list.get(0));

        TestA[] testAS = list.toArray(new TestA[0]);
        TestA[] testA1 = new TestA[list.size()];
        System.arraycopy(testAS, 0, testA1, 0, list.size());
        testA1[0].setName("dd");
        System.out.println(list);


        List<TestA> arrayList = new ArrayList<>(1);
        arrayList.add(new TestA("aaaaaa"));

        List<TestA> objectss = new ArrayList<>(1);
        System.out.println(objectss.size());

        //进行手动扩容
        Collections.addAll(objectss, new TestA[arrayList.size()]);

        Collections.copy(objectss, arrayList);
        objectss.get(0).setName("bbbbb");
        System.out.println(objectss);

        System.out.println(arrayList);
    }

    //深度拷贝  Serializable
    public static <T> List<T> deepTest1(List<T> src) {

        try (
                //字节数组的 流 缓冲区 先存着 字节流
                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                //把对象 进行序列化 的 流
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOut);

                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteOut.toByteArray());
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        ) {
            objectOutputStream.writeObject(src);

            //不编译
            @SuppressWarnings("unchecked")
            List<T> dest = (List<T>) objectInputStream.readObject();

            return dest;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值