java深度复制问题

victortony1991 2013-04-22 10:32:09
我有这样一个类
class elem{
List<elem> child ;
.......

}
我想实现深度复制,重写clone方法
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Elem e = null;
e = (Elem)super.clone();
e.children = new ArrayList<Elem>();
for(int i=0;i<e.children.size();i++){
Elem temp = (Elem)children.get(i).clone();
e.children.add(temp);
}
return e;
}
我想处理多层嵌套的情况,可是上面那个根本没有起作用。求解决方法。
...全文
251 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lcf 2013-04-23
  • 打赏
  • 举报
回复
protected Object clone() throws CloneNotSupportedException {
  Elem e new Elem();
  e.children = new ArrayList<Elem>();
  for (Elem child : this.children) 
    e.children.add(child.clone());
  return e;
 }
你的方法里,注意这两行: e.children = new ArrayList<Elem>(); for(int i=0;i<e.children.size();i++){ e.children是一个新的ArrayList,所以下面这个循环没有效果
STEEL-CHINA 2013-04-23
  • 打赏
  • 举报
回复
引用 楼主 victortony1991 的回复:
我有这样一个类 class elem{ List<elem> child ; ....... } 我想实现深度复制,重写clone方法 protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub Elem e =……
=========================== 如果要完全深度复制,还是用objectinputstream/objectoutputstream对象流,处理吧。
caili314 2013-04-23
  • 打赏
  • 举报
回复
如果效率不是很关键的话, 我会偷懒用(flexjson.jar) new JSONDeserializer().deserialize(new JSONSerializer().deepSerialize(object))
victortony1991 2013-04-23
  • 打赏
  • 举报
回复
引用 1 楼 yangjunloveyu 的回复:
protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub Elem e = null; e = (Elem)super.clone(); if(e.children!=null){ List<elem> tempLi……
谢谢了 我试了一下还是不行。。。
绝对在乎妮 2013-04-23
  • 打赏
  • 举报
回复
用ByteArrayOutputStream和ByteArrayInputStream来读写吧。目测那for循环里也是影子克隆而已,不能达到深度克隆
shine333 2013-04-23
  • 打赏
  • 举报
回复
如果所有子子孙孙都是常见的Serializable的话,建议用序列化/反序列化的方式搞定。序列化到内存数组中,再反向读取,返回出来作为超级深度克隆的产物
小小X 2013-04-22
  • 打赏
  • 举报
回复
protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub Elem e = null; e = (Elem)super.clone(); if(e.children!=null){ List<elem> tempList = new ArrayList<Elem>(); for(int i=0;i<e.children.size();i++){ Elem temp = (Elem)children.get(i).clone(); tempList.add(temp); } e.children = tempList; } return e; }

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧