浅复制和深复制的代码实现



演示一:浅复制

public class Student implements Cloneable {
String name;
int age;

Student(String name, int age) {
this.name = name;
this.age = age;
}

public Object clone() {
Object o = null;
try {
o = (Student) super.clone();// Object中的clone()识别出你要复制的是哪一
// 个对象。
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}

public static void main(String[] args) {
Student s1 = new Student("zhangsan", 18);
Student s2 = (Student) s1.clone();
s2.name = "lisi";
s2.age = 20;
System.out.println("name=" + s1.name + "," + "age=" + s1.age);// 修改学生2后,不影响
// 学生1的值。
}
}

运行结果:name=zhangsan,age=18

演示二:浅复制不能同时复制引用

public class Professor {
String name;
int age;

Professor(String name, int age) {
this.name = name;
this.age = age;
}
}


public class Student1 implements Cloneable {
String name;// 常量对象。
int age;
Professor p;// 学生1和学生2的引用值都是一样的。

Student1(String name, int age, Professor p) {
this.name = name;
this.age = age;
this.p = p;
}

public Object clone() {
Student1 o = null;
try {
o = (Student1) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}

public static void main(String[] args) {
Professor p = new Professor("wangwu", 50);
Student1 s1 = new Student1("zhangsan", 18, p);
Student1 s2 = (Student1) s1.clone();
s2.p.name = "lisi";
s2.p.age = 30;
System.out.println("name=" + s1.p.name + "," + "age=" + s1.p.age);// 学生1的教授
// 成为lisi,age为30。
}
}

运行结果:name=lisi,age=30


演示三:将需要引用的对象也克隆一下做深复制

public class Professor1 implements Cloneable {
String name;
int age;

Professor1(String name, int age) {
this.name = name;
this.age = age;
}

public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
return o;
}
}

运行结果:name=wangwu,age=50


演示四:利用串行化进行深复制

public class Professor2 implements Serializable {
String name;
int age;

Professor2(String name, int age) {
this.name = name;
this.age = age;
}
}


public class Student3 implements Serializable {
String name;// 常量对象。
int age;
Professor2 p;// 学生1和学生2的引用值都是一样的。

Student3(String name, int age, Professor2 p) {
this.name = name;
this.age = age;
this.p = p;
}

public Object deepClone() throws IOException, OptionalDataException,
ClassNotFoundException {
// 将对象写到流里
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
}

public static void main(String[] args) throws OptionalDataException, IOException, ClassNotFoundException {
Professor2 p = new Professor2("wangwu", 50);
Student3 s1 = new Student3("zhangsan", 18, p);
Student3 s2 = (Student3) s1.deepClone();
s2.p.name = "lisi";
s2.p.age = 30;
System.out.println("name=" + s1.p.name + "," + "age=" + s1.p.age); // 学生1的教授不改变。
}

}

运行结果:name=wangwu,age=50

你可能感兴趣的:(OO)