JAVA list 深度拷贝 copy
前言
在开发过程中 会遇到类似 需要操作修改一个list 但是还不想影响原list的情况,这时候就会用到深度copy了。
二、示例代码
1.深度拷贝
代码如下(示例):
public static <T> List<T> deepCopyList(List<T> originalList) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(originalList);
oos.close();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
List<T> deepCopyList = (List<T>) ois.readObject();
return deepCopyList;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}