深拷贝和浅拷贝
都是拷贝a对象为b对象(对象拷贝)
Java中的浅拷贝: 对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝。
要求类对象的类实现Clonable接口,使用clone() 复制 有一个缺陷:复杂属性是以复制引用的方式(简单属性回真实复制)
Java中的深拷贝:对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容。要求类对象的类实现Serializable接口(序列化),此处使用Clonable
浅拷贝:
public class A{
public static void main(String[] args) throws CloneNotSupportedException {
Teacher t = new Teacher("张三",32);
Student s1 = new Student("李四",12,t);
Student s2 = (Student) s1.clone();//浅拷贝
System.out.println(s1);
System.out.println(s2); //s1、s2的名字,年龄相同、老师(张三)均相同
t.setName("张");
System.out.println(s1);
System.out.println(s2);//修改后,s1、s2的老师的名字变为修改后的名字(张)
}
}
class Teacher implements Cloneable{
private String name;
private int age;
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Student implements Cloneable{
private String name;
private int age;
private Teacher teacher;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", teacher=" + teacher +
'}';
}
public Student(String name, int age, Teacher teacher) {
this.name = name;
this.age = age;
this.teacher = teacher;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public Object clone() throws CloneNotSupportedException{
Object o = super.clone();
return o;
}
}
分析:两个引用s1
和s2
指向不同的两个对象,所以s1、s2中name和age的修改彼此互不影响,但是两个引用s1
和s2
中的两个引用指向的是同一个对象t,当t修改后,s1、s2同步修改。
深拷贝:
public class A{
//省去get、set和toString方法
class Teacher implements Cloneable{
private String name;
private int age;
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
class Student implements Cloneable{
private String name;
private int age;
private Teacher teacher
public Object clone() throws CloneNotSupportedException{
Student student = (Student) super.clone();
//将Teacher对象复制一份并重新set进来
student.setTeacher((Teacher) student.getTeacher().clone());
return student;
}
}
使用Object类提供一个clone()方法,可以将Java对象复制一份,因此Java中可以直接使用clone()方法来实现对象的克隆,但是clone()方法是一个protected保护方法,外部类不能直接调用