【发布时间】:2016-08-06 11:58:31
【问题描述】:
我正在我的复制构造函数中尝试这个
protected int forca;
protected Spell []feitico;
public Picareta(final Picareta rValue)
{
super((Ferramenta)rValue);
this.forca=rValue.forca;
this.feitico=rValue.feitico.clone();
}
但是 feitico 具有相同的引用,而不是克隆数组中的对象
我真的需要克隆数组中的每个元素,还是我的 clone() 拼写错误?
public Spell clone() throws CloneNotSupportedException
{
super.clone();
Spell temp= new Spell(this);
return temp;
}
或者这种方式是最好(紧凑)的方式吗?
public Picareta(final Picareta rValue)
{
super((Ferramenta)rValue);
this.forca=rValue.forca;
this.feitico=new Spell[rValue.feitico.length];
for (int i=0;i<rValue.feitico.length;i++)
this.feitico[i]=new Spell(rValue.feitico[i]);
}
【问题讨论】:
-
是的,您确实需要复制数组中的每个元素。
-
那么 clone() 方法只对数组原语有用吗?因为我虽然 array.clone() 应该在它的主体内使用我的 clone() 方法,甚至是复制构造器
-
差不多,是的。假设
clone()完全有用,这……嗯。 (一般来说,最好的做法是让几乎所有东西都是不可变的,在这种情况下你永远不需要复制。) -
现在我明白为什么每个人都说最好不要使用它,我没有节省任何工作,因为无论如何你都可以使用浅拷贝作为基元