深拷贝Java List的方案

在Java中,我们经常需要对List进行深拷贝,以避免对原始数据的影响。深拷贝是指将一个对象复制一份,不仅复制对象本身,还要复制对象包含的所有引用类型的数据。

问题描述

假设我们有一个List,其中包含了多个自定义对象,我们想要对这个List进行深拷贝。

解决方案

方法一:通过序列化实现深拷贝

import java.io.*;

public class DeepCopyUtil {
    public static <T> List<T> deepCopy(List<T> src) {
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
            objectOut.writeObject(src);

            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream objectIn = new ObjectInputStream(byteIn);
            List<T> dest = (List<T>) objectIn.readObject();

            return dest;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}

方法二:通过遍历复制实现深拷贝

public class DeepCopyUtil {
    public static <T> List<T> deepCopy(List<T> src) {
        List<T> dest = new ArrayList<>(src.size());
        for (T elem : src) {
            try {
                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
                objectOut.writeObject(elem);

                ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
                ObjectInputStream objectIn = new ObjectInputStream(byteIn);
                @SuppressWarnings("unchecked")
                T copy = (T) objectIn.readObject();

                dest.add(copy);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        return dest;
    }
}

使用示例

public class Main {

    public static void main(String[] args) {
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("Alice", 25));
        persons.add(new Person("Bob", 30));

        List<Person> deepCopy = DeepCopyUtil.deepCopy(persons);

        // 修改深拷贝后的数据不影响原始数据
        deepCopy.get(0).setName("Carol");
        System.out.println(persons.get(0).getName()); // Output: Alice
        System.out.println(deepCopy.get(0).getName()); // Output: Carol
    }
}

总结

通过上述两种方法,我们可以实现对Java List的深拷贝操作。需要注意的是,如果自定义对象中包含了引用类型的数据,也需要对这些数据进行深拷贝,以确保整个数据结构的完整性。深拷贝在实际开发中非常重要,可以有效避免因共享数据而导致的意外修改。