java中List深拷贝的简单实例

1.实例中用到的类(一定要实现Serializable接口)

class Person implements Serializable{
    private String Name;
    private List<Double> other;
    private int age;

 。。。。省略get set方法
}

2.克隆List的方法

    public static <T> List<T> deepCopy(List<T> src) {
        List<T> dest=null;
        try{
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);
        out.close();

        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        dest = (List<T>) in.readObject();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
        return dest;
    }

3.测试代码即输出结果

List<Double> list=Stream.of(23.6,28.7,21.2).collect(Collectors.toList());
        Person person=new Person();
        person.setName("jerry");
        person.setAge(18);
        person.setOther(list);

        List<Double> list1=Stream.of(45.2,78.6,12.3).collect(Collectors.toList());
        Person p1=new Person();
        p1.setName("tome");
        p1.setAge(20);
        p1.setOther(list1);


        List<Double> list2=Stream.of(99.1,27.7,21.2).collect(Collectors.toList());
        Person p2=new Person();
        p2.setName("Mike");
        p2.setAge(25);
        p2.setOther(list2);


        List<Double> list3=Stream.of(5.6,8.7,1.2).collect(Collectors.toList());
        Person p3=new Person();
        p3.setName("Susan");
        p3.setAge(30);
        p3.setOther(list3);

        List<Person> list_person=Stream.of(person,p1,p2,p3).collect(Collectors.toList());
        List<Person> listclone_p=deepCopy(list_person);
        listclone_p.get(0).setName("Alex");
        listclone_p.get(0).setAge(66);
        listclone_p.get(0).setOther(Arrays.asList(6.6,66.6,666.6));
        list_person.stream().forEach(e->System.out.printf("名字:%s,年龄:%d others1:%.2f \n",e.getName(),e.getAge(),e.getOther().get(0)));
        System.out.println("克隆之后的变化");
        listclone_p.stream().forEach(e->System.out.printf("名字:%s,年龄:%d others1:%.2f \n",e.getName(),e.getAge(),e.getOther().get(0)));
名字:jerry,年龄:18 others1:23.60 
名字:tome,年龄:20 others1:45.20 
名字:Mike,年龄:25 others1:99.10 
名字:Susan,年龄:30 others1:5.60 
克隆之后的变化
名字:Alex,年龄:66 others1:6.60 
名字:tome,年龄:20 others1:45.20 
名字:Mike,年龄:25 others1:99.10 
名字:Susan,年龄:30 others1:5.60 

根据输出结果,可知拷贝的List修改不影响主List.即深拷贝。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值