你的位置:首页 > 软件开发 > Java > java中的深浅克隆

java中的深浅克隆

发布时间:2015-04-07 23:00:34
假设有一个对象object,在某处又需要一个跟object一样的实例object2,强调的是object和object2是两个独立的实例,只是在开始的时候,他们是具有相同状态的(属性字段的值都相同)。遇到这种情况的做法一般是,重新new一个对象object2,将object的字段 ...

java中的深浅克隆

假设有一个对象object,在某处又需要一个跟object一样的实例object2,强调的是object和object2是两个独立的实例,只是在开始的时候,他们是具有相同状态的(属性字段的值都相同)。遇到这种情况的做法一般是,重新new一个对象object2,将object的字段值赋予object2,即:object2=object; 这样的话两个引用仍然指向的是同一个对象,不是两个对象。

克隆方法clone()

Java中跟克隆有关的两个类分别是Cloneable接口和Object类中的clone方法,通过两者的协作来实现克隆。

首先来看看Object的clone()源代码:

  /**   * Creates and returns a copy of this {@code Object}. The default   * implementation returns a so-called "shallow" copy: It creates a new   * instance of the same class and then copies the field values (including   * object references) from this instance to the new instance. A "deep" copy,   * in contrast, would also recursively clone nested objects. A subclass that   * needs to implement this kind of cloning should call {@code super.clone()}   * to create the new instance and then create deep copies of the nested,   * mutable objects.   *   * @return a copy of this object.   * @throws CloneNotSupportedException   *       if this object's class does not implement the {@code   *       Cloneable} interface.   */  protected Object clone() throws CloneNotSupportedException {    if (!(this instanceof Cloneable)) {      throw new CloneNotSupportedException("Class doesn't implement Cloneable");    }    return internalClone((Cloneable) this);  }  /*   * Native helper method for cloning.   */  private native Object internalClone(Cloneable o);

原标题:java中的深浅克隆

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。