java实现对象拷贝的两种方法

拷贝分为浅拷贝和深度拷贝,浅拷贝是实现对象引用的传递,拷贝之后的两个对象指向同一引用,这样的缺点就是修改一个对象的值之后,另一个对象的值也随之改变,但节省内存。深度拷贝是重新开辟空间存放对象的内容,这样可以实现两个对象的改变互不影响。
1.重写Object的clone方法可实现浅拷贝,的克隆代码如下:

public class Student implements Cloneable{
    private String name;

    public static void main(String[] args) throws CloneNotSupportedException {
        Student student = new Student();
        student.setName("张三");
        Student student1 = student.clone();
        System.out.println(student);
        System.out.println(student1);
        System.out.println(student.getName());
        System.out.println(student1.getName());
    }

    @Override
    protected Student clone() throws CloneNotSupportedException {
        return (Student) super.clone();
    }

    public String getName() {
        return name;
    }

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

当然实现Cloneable方法只能实现浅拷贝,若要实现深度克隆需要类及类中的所有成员都要层层实现cloneable接口重写clone方法。这样会显得很不友好,下面我们采用第二种方法实现对象的深度克隆。
2.第二种办法是采用序列化将对象转变成流,输入再输出。将对象序列化为字节序列后,默认会将整个对象进行序列化,再通过反序列化即可完美地实现深拷贝。下面来实现一下。首先我们创建一个Teacher类

import java.io.Serializable;

public class Teacher implements Serializable {
    private String name;
    private int 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;
    }
}

创建一个将对象流输入再输出的工具类

import java.io.*;
public class CloneUtil {
    public static  T clone(T obj) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        ObjectOutput objectOutput = new ObjectOutputStream(ous);
        objectOutput.writeObject(obj);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(ous.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        return (T) objectInputStream.readObject();
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Teacher teacher = new Teacher();
        teacher.setName("李四");
        System.out.println(teacher);
        System.out.println(teacher.getName());

        Teacher teacher1 = CloneUtil.clone(teacher);

        System.out.println(teacher1);
        System.out.println(teacher1.getName());
    }
}

你可能感兴趣的:(java实现对象拷贝的两种方法)