ArrayList中如何对非基本类型的对象深复制的问题,它的clone都是SHALLOW COPY?
例子如下:
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的方法先串形化再取出,感觉有点复杂,还有其他的更好方法吗?