2

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]);
    }
4
  • 3
    Yes, you would really need to copy every element inside the array. Commented Apr 14, 2016 at 18:44
  • then the clone() method is only useful with an array primitives?, because i though the array.clone() were supposed to use my clone() method inside its body or even the copy construtor Commented Apr 14, 2016 at 18:52
  • Pretty much, yes. Assuming clone() is useful at all, which...eh. (Generally speaking, best practice is to make pretty much everything immutable, in which case you never need to copy.) Commented Apr 14, 2016 at 18:53
  • now i understand why everybody says its better not to use it, i saves no work as you can use shallow copy for primitives anyway Commented Apr 14, 2016 at 18:54

2 Answers 2

1

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.