带静态变量的Java克隆
如何为带有静态变量的类编写克隆函数带静态变量的Java克隆,java,Java,如何为带有静态变量的类编写克隆函数 class Vehicle implements Cloneable { private double degree; private double speed; private String owner; private long ID; static private long nextID; Vehicle(){ this.ID = Vehicle.nextID++; }
class Vehicle implements Cloneable {
private double degree;
private double speed;
private String owner;
private long ID;
static private long nextID;
Vehicle(){
this.ID = Vehicle.nextID++;
}
Vehicle(String name) {
this();
owner = name;
}
public Vehicle clone() throws CloneNotSupportedException {
try {
Vehicle v = (Vehicle)super.clone();
v.ID = Vehicle.nextID++;
return v;
} catch(CloneNotSupportedException e){
throw new InternalError(e.toString());
}
}
}
这是正确的实现吗?首先,它不是线程安全的。。。但是,甚至在您引入
clone()
方法之前。最终这取决于你希望这意味着什么。。。我希望使用clone()
来保留现有ID,但可能您有不同的要求。您能详细介绍线程安全吗?ID是唯一的密钥,所以对于克隆对象来说它应该是新的。好吧,在没有任何锁定的情况下改变静态变量是不安全的。来自不同线程的两个调用可能最终使用相同的ID,或其他各种问题。您应该使用AtomicLong
。但从根本上说,如果克隆没有与旧对象相同的数据,我不会将其称为clone()
。