浅克隆
实现Cloneable,重写clone方法时不进行任何操作, 那么调用的clone是进行的浅克隆。
深克隆,创建一个新的对象实例。
使用对象流将对象写入流然后再读出是进行的深克隆。
之前一直迷惑的点是浅克隆会不会创建新对象。事实上克隆操作都是会产生新对象的。但是浅克隆操作不会克隆引用的对象。换句话说,如果在重写clone方法的时候将所有的引用对象都进行浅克隆,那么就变成了深克隆
这种做法在ArrayList 中有体现:
transient Object[] elementData; // non-private to simplify nested class access
/**
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
*
* @return a clone of this <tt>ArrayList</tt> instance
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size); // 因为是Object对象 所以在Clone的时候, elementData并不会clone。为了实现最终效果,需要手动clone。
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
跟一个小例子:
public class TestClone {
public static void main(String[] args) throws CloneNotSupportedException {
TargetOBJ t = new TargetOBJ();
ShallowOBJ s = new ShallowOBJ();
t.set(s);
TargetOBJ t2 = (TargetOBJ) t.clone();
System.out.println(t.get() == t2.get()); // true, 说明引用的是同一个对象
}
}
class TargetOBJ implements Cloneable{
ShallowOBJ obj = null;
public ShallowOBJ get(){
return obj;
}
public void set(ShallowOBJ obj){
this.obj = obj;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
class ShallowOBJ { }