从此将深刻理解shallow clone和 deep clone的区别。
----
package jc8;
import java.util.*;
/**
*listing 6-2
* 这段代码用于演示deepclone和shallowclone。
* clone能够把变量指向的对象另外复制一份,但如果对象中还包含*对象*,则还要将*对象*clone一遍
* 以达到clone的目的。clone的目的是便于操纵clone,而不影响original对象的值
* @author Administrator
*
*/
public class Demon implements Cloneable{
private int bullets;
private String name;
Date bornDate;
public Demon(String aName,int aBullets){
name=aName;
bullets=aBullets;
bornDate=new Date();//GregorianCalendar().getTime();
}
public String getName(){
return name;
}
public int getBullets(){
return bullets;
}
public void setBullets(int aBullets){
bullets=aBullets;
}
public String toString(){
return getClass()+", name:"+name+", bullets:"+bullets+", bornDate"+bornDate;
}
public Demon clone(){
try {
//Object clone, the so called shallow clone
Demon otherDemon=(Demon)super.clone();
//deep clone. if not, the original's bornDate will also be Sun Mar 21 00:00:00 CST 2010
//but we deep cloned, so the original's bornDate is still in year 2003.
otherDemon.bornDate=(Date)bornDate.clone();//
return otherDemon;
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void setBornDate(int year,int month,int day){
//为什么不使用下面的这段代码进行deep clone的演示?
//bornDate=new GregorianCalendar(year,month-1,day).getTime();
//如果果真如上,则无需deepclone,因为上面的new其实已经创建了另外一个新的对象实例
//这个新的对象实例实际上是独立于original的bornDate的。
//也就是说,second.bornDate将指向的是一个新的Date对象,不会对orignal.bornDate产生啥影响了。
Date newBornDate=new GregorianCalendar(year,month-1,day).getTime();
bornDate.setTime(newBornDate.getTime());
}
}