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

apollo333 apollo333 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
例子如下:

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的方法先串形化再取出,感觉有点复杂,还有其他的更好方法吗?
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
apollo333
Java SE 62,621 成员 307,251 内容