Java Deep Clone Shallow Clone 深克隆和浅克隆

Java Deep Clone Shallow Clone 深克隆和浅克隆

为什么要用Clone?

Java通过传递句柄来传参数。当你传递一个对象时实际上是传递了一个方法外的对象句柄,因此当你对方法内的句柄做任何改变的时候实际上就是修改了方法外的对象。此外:

Aliasing happens automatically during argument passing. 别名操作在对象传递过程中自动进行

There are no local objects, only local handles. 没有局部的对象,只有局部的句柄

Handles have scopes, objects do not. 句柄有范围限制,对象没有

Object lifetime is never an issue in Java. Java中对象的生命周期从来不是一个问题

There is no language support (e.g. const) to prevent objects from being modified (to prevent negative effects of aliasing). 没有语言方面的保证使对象免于修改。

同时java是按值传递原始数据,但对于对象传递的则是引用。但我们有时候会希望有一个local的对象而不必修改外面对象,这样就是我们说的clone了。

Java的默认里是浅克隆,也就是只是对象的一个简单clone。但是当一个class里包含复杂的对象时,比如一个School里有teacher和student,那么该就需要深度clone。简单的说,用数据库的角度,如果要用“cascading delete”的那么就要用深克隆,否则就是浅克隆。 一个深克隆的例子如下:

//: DeepCopy.java
// Cloning a composed object

class DepthReading implements Cloneable {
  private double depth;
  public DepthReading(double depth) { 
    this.depth = depth;
  }
  public Object clone() {
    Object o = null;
    try {
      o = super.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return o;
  }
}

class TemperatureReading implements Cloneable {
  private long time;
  private double temperature;
  public TemperatureReading(double temperature) {
    time = System.currentTimeMillis();
    this.temperature = temperature;
  }
  public Object clone() {
    Object o = null;
    try {
      o = super.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    return o;
  }
}

class OceanReading implements Cloneable {
  private DepthReading depth;
  private TemperatureReading temperature;
  public OceanReading(double tdata, double ddata){
    temperature = new TemperatureReading(tdata);
    depth = new DepthReading(ddata);
  }
  public Object clone() {
    OceanReading o = null;
    try {
      o = (OceanReading)super.clone();
    } catch (CloneNotSupportedException e) {
      e.printStackTrace();
    }
    // Must clone handles:
    o.depth = (DepthReading)o.depth.clone();
    o.temperature = 
      (TemperatureReading)o.temperature.clone();
    return o; // Upcasts back to Object
  }
}

public class DeepCopy {
  public static void main(String[] args) {
    OceanReading reading = 
      new OceanReading(33.9, 100.5);
    // Now clone it:
    OceanReading r = 
      (OceanReading)reading.clone();
  }
} ///:~ 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值