文章目录
前言
一、使用序列化
1.创建deepCopy方法
总结
前言
对于复杂对象的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流序列化读写会大大影响程序的执行效率
————————————————
版权声明:本文为优快云博主「weixin_44350816」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/weixin_44350816/article/details/109989851