使用序列化方法实现list集合的深拷贝

对于可序列化(实现Serializable接口)的对象,封装它的list集合可以通过以下方法实现深拷贝


public static List deepCopy(List 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 dest = (List) in.readObject();
return dest;
}


扩展一下,其实只要对象实现了Serializable接口,都可以用序列化的方式实现对象的深拷贝

public static T clone(T t) {
T cloneObj = null;

try {
// 将对象写入字节流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(t);
oos.close();

// 从字节流中读取
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
cloneObj = (T) ois.readObject();

ois.close();
}
catch (Exception e) {
e.printStackTrace();
}

return cloneObj;
}


已有轮子:
Apache的commons-lang包下面的工具类SerializationUtils已经为我们实现了拷贝功能,方法的源码如下:

public static Object clone(Serializable object)
{
return deserialize(serialize(object));
}

其接受的参数object就是Serializable类型的

我们可以直接调用其方法实现对象拷贝(例子中的Student类实现了Serializable接口)

public static void main(String[] args) {
Student student = new Student();
Student clone = (Student) org.apache.commons.lang.SerializationUtils.clone(student);
System.out.println(student.toString());
System.out.println(clone.toString());
}

你可能感兴趣的:(深拷贝,技术前沿)