浅克隆和深克隆

Java-1. 深克隆和浅克隆

深克隆和浅克隆
* 浅克隆:创建一个新对象,新对象的属性和原来对象完全相同,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址(克隆地址)。
*    即:克隆的非基本类型属性发生变化会使两个对象相互影响
* 深克隆:创建一个新对象,属性中引用的其他对象也会被克隆,不再指向原有对象地址(克隆值)。
*    即:克隆的非基本类型属性发生变化不会使两个对象相互影响
public class Student implements Cloneable,Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private Integer age;
    private Teacher teacher;

    .......

    /**
     * 深克隆方式1:对每一个非基本类型进行克隆
     * 思路:1. 实现Cloneable接口
     *       2. 重写clone方法,抛出CloneNotSupportedException异常
     *       3. 对每一个非基本类型属性进行克隆
     *       4. 对每个非基本类型属性所应用的类进行如上操作。
     * 对象简单时可选择该种方式
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Object clone() throws CloneNotSupportedException {
        //return super.clone();
        //1. 深克隆:对每一个非基本类型进行克隆
        Student student = (Student)super.clone();
        student.setTeacher((Teacher) student.getTeacher().clone());
        return student;
    }

    /**
     * 深克隆方式2:利用serializable深复制,将对象写入IO流,再写出
     * 思路:1. 每一个类都要继承Serializable接口
     *       2. 自定义克隆方法,将对象写入对象IO流,再读出IO流
     * 对象复杂时可选择该方式
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    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); //方式1 不变化
        System.out.println(student_clone2);//方式2 不变化
    }
}

你可能感兴趣的:(java)