我的理解: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