Java:
假设有如下文件House.java
public class House implements Cloneable,Comparable{
private int id;
private double area;
private java.util.Date whenBuilt;
public House(int id,double area){
this.id=id;
this.area=area;
whenBuilt = new java.util.Date();
}
public int getId(){
return id;
}
public double getArea(){
return area;
}
public java.util.Date getWhenBuilt(){
return whenBuilt;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public int compareTo(Object o){
if(area>((House)o).area)
return 1;
else if(area<((House)o).area)
return -1;
else
return 0;
}
}
于是,我们可以这样操作:
House house1 = new House(1,1750.50);
House house2 = (House)house1.clone();
System.out.println(house1==house2) --- false //两个不同的对象
Syetem.out.println(house1.whenBuilt==house2.whenBuilt) --- true//引用复制
由此得出浅复制的结论:
如果一个数据域是基本类型,复制的就是它的值;如果一个数据域是对象,复制的就是该域的引用。
为了实现深复制,可进行如下操作:
@Override
public Object clone() throws CloneNotSupportedException{
try{
House house = (House)super.clone();
house.whenBuilt = (java.util.Date)(whenBuilt.clone());
return house;
}catch(CloneNotSupportedException e){
return null;
}
}
于是进行相同操作后得:
Syetem.out.println(house1.whenBuilt==house2.whenBuilt) --- false //值复制
值得注意的是,如果House没有覆盖clone()方法,程序就会收到一个语法错误,因为在java.lang.Object中clone()是被保护的。其原型为protected native Object clone() throws CloneNotSupportedException。如果House不实现java.lang.Cloneable,调用House.java的super.clone()会导致一个CloneNotSupportedException异常。为了克隆一个对象,该对象的类必须覆盖clone()方法并实现Cloneable
网友评论