dev*_*ium 12 java clone cloneable
In Effective Java, the author states that:
If a class implements Cloneable, Object's clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException.
What I'd like to know is what he means with field-by-field copy. Does it mean that if the class has X bytes in memory, it will just copy that piece of memory? If yes, then can I assume all value types of the original class will be copied to the new object?
class Point implements Cloneable{
private int x;
private int y;
@Override
public Point clone() {
return (Point)super.clone();
}
}
Run Code Online (Sandbox Code Playgroud)
If what Object.clone()
does is a field by field copy of the Point
class, I'd say that I wouldn't need to explicitly copy fields x
and y
, being that the code shown above will be more than enough to make a clone of the Point
class. That is, the following bit of code is redundant:
@Override
public Point clone() {
Point newObj = (Point)super.clone();
newObj.x = this.x; //redundant
newObj.y = this.y; //redundant
}
Run Code Online (Sandbox Code Playgroud)
Am I right?
I know references of the cloned object will point automatically to where the original object's references pointed to, I'm just not sure what happens specifically with value types. If anyone could state clearly what Object.clone()
's algorithm specification is (in easy language) that'd be great.
是的,字段副本的字段确实意味着当它创建新的(克隆的)对象时,JVM会将原始对象中每个字段的值复制到克隆的对象中.不幸的是,这确实意味着你有一个浅的副本.如果需要深层复制,可以覆盖克隆方法.
class Line implements Cloneable {
private Point start;
private Point end;
public Line() {
//Careful: This will not happen for the cloned object
SomeGlobalRegistry.register(this);
}
@Override
public Line clone() {
//calling super.clone is going to create a shallow copy.
//If we want a deep copy, we must clone or instantiate
//the fields ourselves
Line line = (Line)super.clone();
//assuming Point is cloneable. Otherwise we will
//have to instantiate and populate it's fields manually
line.start = this.start.clone();
line.end = this.end.clone;
return line;
}
}
Run Code Online (Sandbox Code Playgroud)
克隆的另一个重要事项是,永远不会调用克隆对象的构造函数(只复制字段).因此,如果构造函数初始化外部对象,或者使用某个注册表注册此对象,那么克隆对象就不会发生这种情况.
我个人更喜欢不使用Java的克隆.相反,我通常会创建自己的"复制"方法.
归档时间: |
|
查看次数: |
4260 次 |
最近记录: |