提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
对于复杂对象的ArrayList如何进行深拷贝。
首先对需要序列化的类及其属性包含的类实现序列化接口
implements Serializable
例如:
class Cast implements Serializable{
private LinkedList<Charge> Charges;
}
class Charge implements Serializable
一、使用序列化
1.创建deepCopy方法
代码如下:
/**
* 深克隆Cast对象
* @param src 深克隆目标
* @return 克隆后的List
* @throws IOException
* @throws ClassNotFoundException
*/
public 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);
List dest = (List)in.readObject();
return dest;
}
调用此方法时代码如下。
List<Cast> castCode = null;
try {
castCode = test.deepCopy(tempcast);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
总结
通过序列化可以对当前已有复杂对象实现完全的深克隆,但是仅限于自用的小规模情况,频繁使用IO流序列化读写会大大影响程序的执行效率