Java的对象拷贝-Clone

Clone可以拷贝出一个对象的副本,它有分浅拷贝(Shallow copy)和深拷贝(Deep copy),
Clone是如何进行拷贝呢?
1:Object类本身是不实现Cloneable接口的,所以在类为 Object 的对象上调用 clone 方法将会导致在运行时抛出CloneNotSupportedException。
2:Object在对某个对象实施Clone时对其是一无所知的,它仅仅是简单地执行域对域的copy, 这就是Shallow Clone.对于对象中基本类型的变量,浅拷贝(Shallow copy)是没问题的,但是对于一些reference变量,尽管经过clone之后会产生一个新的reference变量,但它和原始对象中对应的域指向同一个reference对象,它和原始对象中对应的域指向同一个Date对象。
例子:
Grade实体类:



package objectclone;


public class Grade implements Cloneable {
private String grade;
private int number;

public String getGrade() {
return grade;
}

public void setGrade(String name) {
this.grade = name;
}

public int getNumber() {
return number;
}

public void setNumber(int number) {
this.number = number;
}
public Object Clone(){
try{
super.clone();
return super.clone();
}
catch(Exception e){
return null;
}
}
}

Person实体类:



package objectclone;

public class Person implements Cloneable{
private String sex;
private int age;
public Grade c;

public Person(String sex,int age,Grade c){
this.sex=sex;
this.age = age;
this.c = c;
}
public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public Grade getC() {
return c;
}

public void setC(Grade c) {
this.c = c;
}
public Object Clone(){
try{
super.clone();
return super.clone();
}
catch(Exception e){
return null;
}
}
}


package objectclone;

public class ShallowClone{
public static void main(String[] args) throws CloneNotSupportedException{
Grade c = new Grade();
Person person = new Person("male",25,c);
Person personcopy = (Person)person.Clone();
person.c.setGrade("grade1");
personcopy.c=(Grade)person.c.Clone();//对reference对象进行拷贝
personcopy.c.setGrade("grade2");
personcopy.setSex("female");
personcopy.setAge(24);
System.out.print("person sex :"+person.getSex());
System.out.println(" personcopy sex:"+personcopy.getSex());
System.out.print("person age:"+person.getAge());
System.out.println(" personcopy age:"+personcopy.getAge());
System.out.print("person grade:"+person.c.getGrade());
System.out.print(" personcopy grade:"+personcopy.c.getGrade());
}

}

以上执行结果:
person sex :male personcopy sex:female
person age:25 personcopy age:24
person grade:grade1 personcopy grade:grade2
若" //personcopy.c=(Grade)person.c.Clone();",执行结果未:
person sex :male personcopy sex:female
person age:25 personcopy age:24
person grade:grade2 personcopy grade:grade2

你可能感兴趣的:(JDK)