java clone初始

首先看這段代碼

public class Test {
    public static void main(String[] args) {
        int a = 5;
        int b = a;
        System.out.println(a == b);

        Student m = new Student();
        Student n = m;
        System.out.println(m == n);
    }
}

可以發現我們爲了clone一個一樣類型的變量,使用了賦值語句,那麼,java中可以不用 = 就可以創建個一樣的對象嗎?答案是肯定的。我們可以讓這個類實現cloneable這個接口,就可以對對象自身進行復制。這個接口自身並沒有方法,只是個聲明,當有這個接口是說明這個類可以對自身進行復制。
這是cloneable接口的源碼

 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   JDK1.0
 */
public interface Cloneable {
}

那麼怎麼實現這個接口呢?如下

public class Student implements Cloneable {
private int id;

private String username;

public Student() {
}

public Student(int id, String username) {
    this.id = id;
    this.username = username;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public Object clone(){
    try {
        //這裏方便大家理解
        Student s = (Student) super.clone();
        return s;
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
        return null;
    }
}

給大家做個測試

public class Test {
    public static void main(String[] args) {
       Student a = new Student();
       Student b = (Student) a.clone();
       System.out.println(a == b);
    }
}

輸出的結果是false,說明通過clone這個方法我們創建了一個新的對象,但是這並不是真正的clone,我們接着看

public class Test {
    public static void main(String[] args) {
       Student a = new Student();
       Student b = (Student) a.clone();
       System.out.println(a == b);
       System.out.println(a.getUsername() == b.getUsername());
    }
}

輸出結果是

false
true

說明clone只是對對象進行了複製,並沒有對對象裏的對象進行復制,那麼要怎麼要對對象裏的對象進行復制呢?

public class Student implements Cloneable {
    private int id;

    private String username;

    private Student student;

    public Student() {
    }

    public Student(int id, String username) {
        this.id = id;
        this.username = username;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Object clone(){
        try {
            Student s = (Student) super.clone();
            s.student = (Student) this.student.clone();
            return s;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
}

這樣就對對象就行了全部複製。

感想:通過這次對字符串的池有些理解了。現在我認爲java是一種對引用進行操作的語言。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章