您的位置:首页 > 编程语言 > Java开发

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

2011-01-12 16:15 477 查看
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();
}
} ///:~


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: