Tiago Mendes da Silva
Tiago Mendes da Silva

Reputation: 23

java clone() with array

i am trying this in my copy constructor

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

but feitico has the same references instead of cloning the objects in the array

do i really need to clone every element inside the array , or is my clone() for Spell wrong ?

public Spell clone() throws CloneNotSupportedException
    {
        super.clone();
        Spell temp= new Spell(this);
        return temp;
    }

or is this way the best(compact) way to make it ?

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

Upvotes: 2

Views: 155

Answers (2)

Paul Boddington
Paul Boddington

Reputation: 37645

clone for arrays of reference type is only a shallow copy, so yes you will need to copy every element inside the array.

You already have a copy constructor for Spell, so this is not too hard.

Using Java 8, there is a nice way to copy a Spell[]:

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

With Java 7 and below, your way cannot be improved.

Upvotes: 1

dsh
dsh

Reputation: 12213

The method .clone() on an array object will clone the array. That does not clone other objects, namely the objects referred to by elements in the array.

What you are asking about is a "deep copy" or "deep clone". After creating a new array to hold the new objects, then you need to iterate through the old array and clone each of the objects referred to there:

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

Upvotes: 1

Related Questions