记录下 深复制 的代码,详细可参考这篇 List 浅拷贝与深拷贝:
深拷贝的方法
1.使用序列化方法
public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(src);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
@SuppressWarnings("unchecked")
List<T> dest = (List<T>) in.readObject();
return dest;
}
List<Person> destList=deepCopy(srcList); //调用该方法
2.clone方法
public class A implements Cloneable {
public String name[];
public A(){
name=new String[2];
}
public Object clone() {
A o = null;
try {
o = (A) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
for(int i=0;i<n;i+=){
copy.add((A)src.get(i).clone());
}
本文介绍了Java中实现对象深拷贝的两种方法:序列化和克隆。通过序列化方式创建深拷贝,可以避免原始对象与副本间的引用问题。而使用克隆方法需要实现`Cloneable`接口,并覆盖`clone()`方法。这两种方法对于复杂对象的复制至关重要,确保了对象的独立性和数据安全性。
3312

被折叠的 条评论
为什么被折叠?



