Java-1. 深克隆和浅克隆
深克隆和浅克隆
* 浅克隆:创建一个新对象,新对象的属性和原来对象完全相同,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址(克隆地址)。
* 即:克隆的非基本类型属性发生变化会使两个对象相互影响
* 深克隆:创建一个新对象,属性中引用的其他对象也会被克隆,不再指向原有对象地址(克隆值)。
* 即:克隆的非基本类型属性发生变化不会使两个对象相互影响
public class Student implements Cloneable,Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
private Teacher teacher;
.......
@Override
public Object clone() throws CloneNotSupportedException {
Student student = (Student)super.clone();
student.setTeacher((Teacher) student.getTeacher().clone());
return student;
}
public Object deepClone() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
}
public class Teacher implements Cloneable,Serializable {
private String name;
private Integer age;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class CloneDemo {
public static void main(String []args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
Teacher teacher1 = new Teacher("张三",20);
Student student1 = new Student();
student1.setTeacher(teacher1);
Student student_clone = (Student) student1.clone();
Student student_clone2 = (Student) student1.deepClone();
System.out.println(student_clone);
System.out.println(student_clone2);
teacher1.setName("李四");
System.out.println(student_clone);
System.out.println(student_clone2);
}
}