java 带数组的 clone()

java clone() with array

我正在我的复制构造函数中尝试这个

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() for Spell 错误?

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() 将克隆该数组。这不会克隆其他对象,即数组中元素引用的对象。

你问的是"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();
    }

clone 对于引用类型的数组只是一个浅拷贝,所以是的,你需要复制数组中的每个元素。

您已经有了 Spell 的复制构造函数,所以这并不难。

使用Java 8,有一个很好的方法来复制一个Spell[]:

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

Java 7 及以下,您的方法无法改进。