2016-04-14 91 views
2

我在我的拷贝构造函数的java的clone()与数组

protected int forca; 
protected Spell []feitico; 
public Picareta(final Picareta rValue) 
    { 
     super((Ferramenta)rValue); 
     this.forca=rValue.forca; 
     this.feitico=rValue.feitico.clone(); 
    } 

想这一点,但feitico具有相同的参考而非阵列

在克隆的对象我真的需要克隆的每一个元素在数组中,还是我的克隆()为拼写错误?

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]); 
    } 
+3

是的,你真的需要复制数组内的每个元素。 –

+0

那么clone()方法只对数组基元?有用,因为我通过array.clone()应该在其内部使用我的clone()方法,或者甚至是复制构造函数 –

+0

。假设'clone()'完全有用,哪个...呃。 (一般来说,最好的做法是使几乎所有东西都是不变的,在这种情况下,你永远不需要复制。) –

回答

1

对数组对象的方法.clone()将克隆该数组。这不会克隆其他对象,即数组中元素引用的对象。

你在问什么是"deep copy" or "deep clone"。创建一个新的数组来保存新的对象后,那么你就需要通过旧数组迭代和克隆每个对象的简称有:

this.feitico = new Spell[rValue.feitico.length]; 
for (int i = 0; i < this.feitico.length ; i += 1) 
    { 
    this.feitico[i] = rValue.feitico[i].clone(); 
    } 
1

clone参考类型的数组只是一个浅拷贝,所以是的,你需要复制数组内的每个元素。

你已经有了Spell的拷贝构造函数,所以这不是太难。

使用Java 8中,是复制一个很好的方式Spell[]

this.feitico = Arrays.stream(rValue.feitico).map(Spell::new).toArray(Spell[]::new); 

在Java 7和下方,用自己的方式不能得到改善。