下面是一个例子。
class DepthReading implements Cloneable{
private double depth ;
public DepthReading(double depth){
this.depth = depth ;
}
public Object clone (){
Object o = null ;
try {
o = super.clone() ;
} catch (CloneNotSupportedException e) {
e.printStackTrace() ;
}
return o;
}
}
class TempReading implements Cloneable{
private long time ;
private double temp ;
public TempReading(double temp ){
this.time= System.currentTimeMillis() ;
this.temp = temp ;
}
public Object clone() {
Object o= null ;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
}
class OceanReading implements Cloneable {
private DepthReading depth ;
private TempReading temp ;
public OceanReading( double ddata, double tdata){
temp = new TempReading(tdata) ;
depth = new DepthReading(ddata) ;
}
public Object clone (){
OceanReading o = null ;
try {
o = (OceanReading )super.clone() ;
} catch (CloneNotSupportedException e) {
e.printStackTrace() ;
}
//must clone handles
o.depth = (DepthReading)o.depth.clone() ;
o.temp = (TempReading)o.temp.clone() ;
return o;
}
}
public class DeepCopy {
public static void main (String [] args ){
OceanReading reading = new OceanReading(33.9,100.5) ;
//clone it
OceanReading r = (OceanReading) reading.clone() ;
}
}
对 Vector 进行深层复制的先决条件: 在克隆了 Vector 后,必须在其中遍历,并克隆
由 Vector 指向的每个对象。为了对 Hashtable(散列表)进行深层复制,也必须采取类似的处理。
这个例子剩余的部分显示出克隆已实际进行——证据就是在克隆了对象以后,可以自由改变它,而原来那个
对象不受任何影响。
若在一个对象序列化以后再撤消对它的
序列化,或者说进行装配,那么实际经历的正是一个“克隆”的过程。
那么为什么不用序列化进行深层复制呢?下面这个例子通过计算执行时间对比了这两种方法:
原文:http://www.cnblogs.com/chuiyuan/p/4362571.html