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.即深拷贝。

猜你喜欢

转载自blog.csdn.net/wsj_jerry521/article/details/109860953