ArrayList中如何对非基本类型的对象深复制的问题,它的clone都是SHALLOW COPY?

apollo333 2005-03-18 07:10:49
例子如下:

import java.util.ArrayList;
import java.util.Date;


public class TTT {

public static void main(String[] args){
TTT t = new TTT();
t.run();
}

public void run(){
ArrayList al = new ArrayList();
al.add(new Date());
al.add(new Date());

//ArrayList shallow = new ArrayList(al);
ArrayList shallow = (ArrayList)al.clone();

for(int i=0;i<shallow.size();i++)
System.out.println("the shallow copy is " +shallow.get(i));

((Date)shallow.get(0)).setTime(0);

for(int i=0;i<shallow.size();i++)
System.out.println("the modified shallow copy is " +shallow.get(i));

for(int i=0;i<shallow.size();i++)
System.out.println("the al is " +al.get(i));
}

}


下面是运行结果:
the shallow copy is Thu Mar 17 23:04:41 GMT 2005
the shallow copy is Thu Mar 17 23:04:41 GMT 2005
the modified shallow copy is Thu Jan 01 01:00:00 GMT 1970
the modified shallow copy is Thu Mar 17 23:04:41 GMT 2005
the al is Thu Jan 01 01:00:00 GMT 1970
the al is Thu Mar 17 23:04:41 GMT 2005

可以看到对shallow的改动影响了原ARRAYLIST。这是典型的浅复制。我想实现深复制,怎么做,就是说对shallow的改动,不影响al这个。在《JAVA与模式》书里提到用Serializable的方法先串形化再取出,感觉有点复杂,还有其他的更好方法吗?
...全文
240 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhshdc 2005-03-18
  • 打赏
  • 举报
回复
Serialize一下不复杂的
fog628 2005-03-18
  • 打赏
  • 举报
回复
//shallow copy
ArrayList shallow = (ArrayList)al.clone();
//deep copy
for(int i = 0; i < al.size(); i++)
shallow.set(i,((Date)al.get(i)).clone());
}
kingfish 2005-03-18
  • 打赏
  • 举报
回复
shallow.set(i,((Date)al.get(i)).clone());

62,635

社区成员

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

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