我的理解:java
深拷貝和淺拷貝一樣是重寫Object的Clone方法,這裏必需要重寫,由於Object的Clone方法是Protected類型的,在本類沒法訪問基類受保護的方法。深拷貝和淺拷貝意義基本相同,只是深拷貝相對淺拷貝來講拷貝的層次要深,深拷貝對類引用的類也進行了拷貝,也就是引用的類也實現了Clone方法,沒有完全的深拷貝,而淺拷貝當前對象不一樣,而引用的對象仍是指向同一個內存地址。ide
例以下面Person類:this
public class Person implements Cloneable{ private int age ; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public Person() {} public int getAge() { return age; } public String getName() { return name; } @Override protected Object clone() throws CloneNotSupportedException { return (Person)super.clone(); } }
實現Cloneable接口,code
Person p = new Person(23, "zhang"); Person p1 = (Person) p.clone(); System.out.println("p.getName().hashCode() : " + p.getName().hashCode()); System.out.println("p1.getName().hashCode() : " + p1.getName().hashCode()); String result = p.getName().hashCode() == p1.getName().hashCode() ? "clone是淺拷貝的" : "clone是深拷貝的"; System.out.println(result);
打印結果爲: p.getName().hashCode() : 115864556
p1.getName().hashCode() : 115864556
clone是淺拷貝的對象
因此,clone方法執行的是淺拷貝, 在編寫程序時要注意這個細節。深拷貝接口
static class Body implements Cloneable{ public Head head; public Body() {} public Body(Head head) {this.head = head;} @Override protected Object clone() throws CloneNotSupportedException { Body newBody = (Body) super.clone(); newBody.head = (Head) head.clone(); return newBody; } } static class Head implements Cloneable{ public Face face; public Head() {} public Head(Face face){this.face = face;} @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public static void main(String[] args) throws CloneNotSupportedException { Body body = new Body(new Head()); Body body1 = (Body) body.clone(); System.out.println("body == body1 : " + (body == body1) ); System.out.println("body.head == body1.head : " + (body.head == body1.head)); }
打印結果爲: body == body1 : false
body.head == body1.head : false內存
因而可知, body和body1內的head引用指向了不一樣的Head對象, 也就是說在clone Body對象的同時, 也拷貝了它所引用的Head對象, 進行了深拷貝。get
以此類推,將引用到的對象都實現Clone方法,就能實現深拷貝, 越深刻拷貝則越深。hash