【发布时间】:2015-05-18 21:09:53
【问题描述】:
对于下面的类,当我做深拷贝的时候,代码写成这样安全吗
this.id = original.getId();
在我的测试中,它似乎没问题,因为当我想更新 UUID 字段时,我总是为它分配一个新的 UUID 实例(我找不到任何可以修改现有 UUID 实例的函数)。在这种情况下,这个复制的将永远不会对原始实例产生副作用。
public class Container {
private Type type;
private UUID id;
private Container c;
// public constructors here
protected Container(Container original, boolean deepCopy) {
this.type = original.getType();
this.id = original.getId();
// for deep copy of id field, should I write as:
// this.id = new UUID(original.getId().getMostSignificantBits(), original.getId().getLeastSignificantBits());
if (original.getC() != null) {
this.c = deepCopy ? original.getC().deepCopy() : original.getC();
}
}
// getter and setter here
public Container deepCopy() {
return new Container(this, true);
}
}
但是在我现在维护的项目中(不是我创建的),我发现深拷贝代码是这样的:
this.id = new UUID(original.getId().getMostSignificantBits(), original.getId().getLeastSignificantBits());
毫无疑问,这是一个正确的解决方案。
我的问题是:这样做安全吗
this.id = original.getId();
也许这是一个愚蠢的问题,感谢您抽出时间来帮助我。
【问题讨论】: