贴一个我觉得这个知识点写的很好的博文:
(看了这些大佬的知识总结,不由感概自己要学的东西真的有很多很多)
Java的对象拷贝
实现深度拷贝的实例:
public class Copy {
public static void main(String[] args) throws CloneNotSupportedException {
ThirdLevel third=new ThirdLevel(10,20);
SecondLevel second=new SecondLevel(1,2.2,third);
FirstLevel first=new FirstLevel(30,0.5,second);
//Java直接输出一个类的对象的时候,会自动调用这个类的toString方法
System.out.println("原对象:"+first);
//利用clone方法进行复制
FirstLevel first2=(FirstLevel)first.clone();
System.out.println("克隆对象:"+first2);
//修改原始对象
second.secondIntValue=10000;
third.thirdIntValue=-100;
System.out.println("修改后的原对象:"+first);
System.out.println("修改后的克隆对象:"+first2);
}
}
class FirstLevel implements Cloneable {
int firstIntValue;
double firstDoubleValue;
SecondLevel second;
public FirstLevel(int firstIntValue, double firstDoubleValue, SecondLevel second) {
this.firstIntValue = firstIntValue;
this.firstDoubleValue = firstDoubleValue;
this.second = second;
}
@Override
protected Object clone() throws CloneNotSupportedException {
//利用Object的Clone方法,复制first对象本身
FirstLevel first = (FirstLevel) super.clone();
//再利用SecondLevel实现的深度克隆clone()方法,完成对second所指向对象的深度克隆
first.second=(SecondLevel)second.clone();
return first;
}
public String toString(){
return "firstIntValue="+firstIntValue+" "+
"firstDoubleValue="+firstDoubleValue+" "+
"second="+second+" ";
}
}
class SecondLevel implements Cloneable{
int secondIntValue;
double secondDoubleValue;
ThirdLevel third;
public SecondLevel(int secondIntValue, double secondDoubleValue,
ThirdLevel third) {
this.secondIntValue = secondIntValue;
this.secondDoubleValue = secondDoubleValue;
this.third = third;
}
@Override
protected Object clone() throws CloneNotSupportedException {
//利用Object的clone方法,先克隆自己本身
SecondLevel second = (SecondLevel) super.clone();
//再利用ThirdLevel实现的深度克隆clone()方法,完成对thridlevel所指向对象的深度克隆
second.third=(ThirdLevel)third.clone();
return second;
}
public String toString(){
return "SecondIntValue="+secondIntValue+" "+
"secondDoubleValue="+secondDoubleValue+" "+
"third="+third+" ";
}
}
class ThirdLevel implements Cloneable{
int thirdIntValue;
double thirdDoubleValue;
public ThirdLevel(int thirdIntValue, double thirdDoubleValue) {
this.thirdIntValue = thirdIntValue;
this.thirdDoubleValue = thirdDoubleValue;
}
protected Object clone() throws CloneNotSupportedException {
ThirdLevel third = (ThirdLevel)super.clone();
return third;
}
public String toString(){
return "thirdIntValue="+thirdIntValue+" "+
"thirdDoubleValue="+thirdDoubleValue;
}
}
输出结果: