/**
...
* Invoking Object's clone method on an instance that does not
* implement the <code>Cloneable</code> interface results in the
* exception
* <code>CloneNotSupportedException</code> being thrown.
* ...
*/
public interface Cloneable {
}
简单翻译就是:如果一个类调用clone()方法,必须先要实现Cloneale这个接口。
public class Object {
protected Object clone() throws CloneNotSupportedException {
if (!(this instanceof Cloneable)) {
throw new CloneNotSupportedException("Class " + getClass().getName() +
" doesn't implement Cloneable");
}
return internalClone();
}
}
浅拷贝:拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。
深拷贝:拷贝对象和对象包含的引用指向的所有对象。
举例来说更加清楚:对象A1中包含对B1的引用。浅拷贝A1得到A2,A2 中依然包含对B1的引用。深拷贝则是对浅拷贝的递归,深拷贝A1得到A2,A2中包含对B2(B1的copy)的引用。
代码表示:
浅拷贝
public class B implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class A implements Cloneable {
private B b;
public A() {
this.b = new B();
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
A a1 = new A();
A a2 = (A) a1.clone();
System.out.println("a1:" + a1.hashCode());
System.out.println("a2:" + a2.hashCode());
System.out.println("a1.b:" + a1.getB().hashCode());
System.out.println("a2.b:" + a2.getB().hashCode());
}
}
打印结果:
a1:1265094477
a2:2125039532
a1.b:312714112
a2.b:312714112
可以看出,a1和a2都是指向同一个b的引用。
深拷贝
修改上面A中clone()方法:
@Override
protected Object clone() throws CloneNotSupportedException {
A a = (A) super.clone();
a.setB((B) b.clone());
return a;
}
打印结果:
a1:1265094477
a2:2125039532
a1.b:312714112
a2.b:692404036
可以看出,a2,a2.b都是拷贝后的引用。