Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 中的克隆:淺複製、深複製與序列化實現

一、為什麼需要克隆

既然單純的引用賦值也可以拿到物件,為什麼還要克隆?先看一個 Student 類別:

public class Student implements Cloneable {

    private String studentName;
    private int age;

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String getStudentName() { return studentName; }
    public void setStudentName(String studentName) { this.studentName = studentName; }
}

入口函數:

public static void main(String args[]) {
    Student student0 = new Student();
    student0.setStudentName("xiaoming");
    Student student1 = student0;
    System.out.println("student0.getStudentName:" + student0.getStudentName());
    System.out.println("student1.getStudentName:" + student1.getStudentName());
}

輸出兩行都是 xiaoming。因為 student1 和 student0 指向記憶體中同一塊空間,透過兩者操作物件完全等價。

但我們常常需要一個內容一模一樣、之後可以獨立修改而不影響原本的副本,這時候就要用 clone。clone 方法定義在 Object 中,但要呼叫它必須先實作 Cloneable 介面,否則會拋出 java.lang.CloneNotSupportedException。

public class Student implements Cloneable {

    private String studentName;
    private int age;

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String getStudentName() { return studentName; }
    public void setStudentName(String studentName) { this.studentName = studentName; }

    public Object clone() throws CloneNotSupportedException {
        Student student = (Student) super.clone();
        return student;
    }
}

public static void main(String args[]) {
    Student student = new Student();
    student.setAge(10);
    student.setStudentName("xiaobai");
    try {
        Student s1 = (Student) student.clone();
        s1.setStudentName("xiaohei");
        System.out.println("student.studentName:" + student.getStudentName());
        System.out.println("student.age:" + student.getAge());
        System.out.println("s1.studentName:" + s1.getStudentName());
        System.out.println("s1.age:" + s1.getAge());
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
}

輸出顯示 s1 的名字被改成 xiaohei,而 student 仍是 xiaobai——這就是克隆的效果。用法很簡單:實作 Cloneable、加上 clone 方法並在內部呼叫 super.clone(),同時記得處理 CloneNotSupportedException。

二、clone() 的三個約定

⑴ clone 會複製一份物件並回傳給呼叫者。一般而言它滿足:
① 對任何物件 x,x.clone() != x(克隆物件與原物件不是同一個);
② 對任何物件 x,x.clone().getClass() == x.getClass()(型別相同);
③ 若 x 的 equals() 定義恰當,則 x.clone().equals(x) 應成立。

⑵ 在 Java 中實作物件克隆的四個步驟:
① 利用 Object 類的 clone() 方法取得拷貝;
② 在派生類中覆寫 clone() 並宣告為 public;
③ 在派生類的 clone() 中呼叫 super.clone();
④ 在派生類中實作 Cloneable 介面。

三、淺克隆與深克隆

淺複製(淺克隆):被複製物件的所有變數都含有與原物件相同的值,但所有對其他物件的引用仍然指向原物件。換句話說,它只複製所考量的物件本身,不複製被引用的物件。

深複製(深克隆):被複製物件的所有變數都含有與原物件相同的值,除了那些引用其他物件的變數——它們會指向被複製出來的新物件。也就是把被引用物件也一起複製了一遍。

說明:
① 覆寫 clone() 時一定要呼叫 super.clone(),因為在執行期,Object 的 clone() 會辨識你要複製哪一種物件,為它配置空間並把內容一一複製過去。
② 繼承自 java.lang.Object 的 clone() 是淺複製。以下程式碼可以證明:

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

class Student implements Cloneable
{
    String name;          // 常量子物件
    int age;
    Professor p;       // 學生 1 與學生 2 的引用值相同

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

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

public static void main(String[] args)
{
    Professor p = new Professor("wangwu", 50);
    Student s1 = new Student("zhangsan", 18, p);
    Student s2 = (Student) s1.clone();
    s2.p.name = "lisi";
    s2.p.age = 30;
    // 學生 1 的教授也被改成 lisi、30 歲
    System.out.println("name=" + s1.p.name + ",age=" + s1.p.age);
}

要讓修改 s2 的教授不影響 s1,就得讓被引用的 Professor 也實作 Cloneable 並在 Student.clone() 中呼叫 p.clone(),也就是深層克隆:

class Professor implements Cloneable
{
    String name;
    int age;
    Professor(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;
    }
}

class Student implements Cloneable
{
    String name;
    int age;
    Professor p;

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

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

public static void main(String[] args)
{
    Professor p = new Professor("wangwu", 50);
    Student s1 = new Student("zhangsan", 18, p);
    Student s2 = (Student) s1.clone();
    s2.p.name = "lisi";
    s2.p.age = 30;
    // 學生 1 的教授維持不變
    System.out.println("name=" + s1.p.name + ",age=" + s1.p.age);
}

四、用序列化做深複製

把物件寫進串流的過程叫序列化(Serialization),Java 圈的說法很形象:「冷凍」或「醃鹹菜」;從串流讀回來的反序列化(Deserialization)則叫「解凍」或「回鮮」。寫進串流的是物件的一份拷貝,原物件仍在 JVM 裡,所以「醃」的只是拷貝,鹹菜還能回鮮。

在 Java 中深複製一個物件,常見做法是讓它實作 Serializable,把物件寫進串流再讀出來,就能重建物件:

public Object deepClone()
{
    // 把物件寫進串流
    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());
}

前提是物件本身以及內部所有引用到的物件都可序列化,否則得仔細評估那些不可序列化的成員能否標成 transient 排除在複製過程之外。改寫後的例子:

class Teacher implements Serializable {
    String name;
    int age;
    Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

class Student implements Serializable {
    String name;               // 常量子物件
    int age;
    Teacher t;

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

    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) {
    Teacher t = new Teacher("tangliang", 30);
    Student s1 = new Student("zhangsan", 18, t);
    Student s2 = (Student) s1.deepClone();
    s2.t.name = "tony";
    s2.t.age = 40;
    // 學生 1 的老師維持不變
    System.out.println("name=" + s1.t.name + ",age=" + s1.t.age);
}
Copyright © Linux教程網 All Rights Reserved