0

Hello I have a class called Ladrillo and in another class I have a 2d array type Ladrillo. I want to clone that array so that if the original one changes this one doesnt.

From what I read online in my ladrillo class I have to put Implements clonable. I did that and the following code but it didn't work:

Ladrillo [][] copy=new Ladrillo[original.length][original.length];

for(int i=0;i<original.length;i++){
  for(int j=0;j<original.length;j++){
   Ladrillo newLadrillo=original[i][j].clone();
   copy[i][j]=newLadrillo;
 }}

Any ideas on what to change? I believe I have to add something on the class Ladrillo but I haven't figured it out. Thanks!

Smit
  • 4,685
  • 1
  • 24
  • 28
Palmera
  • 1
  • 1
  • What does it mean by _it didn't work:_? Please specify exact problem you are facing, What do you expect and what is currently happening? – Smit Oct 22 '13 at 19:44

2 Answers2

0

Have you tried a copy constructor? What language are you using?

See What is a copy constructor in C++?

Community
  • 1
  • 1
dlee777
  • 11
  • 2
0

The clone() method only creates a shallow copy of Arrays if its values are not primitives. For a deep copy you could use the static method

java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 

or implement the clone() method in your Ladrillo class. Here comes an example for a class called Player with two fields that should be copied when the clone() method is called. We're simply calling its superclass ( which is java.lang.Object for the Player class) clone() - method and cast the result to Player.

public class Player implements Cloneable {
   public String name;
   public int    age;

  @Override
  public Player clone() {
    try {
     return (Player) super.clone();
    }
    catch ( CloneNotSupportedException e ) { // its cloneable
     throw new InternalError();
    }
  }
}
Gernot
  • 1,094
  • 4
  • 25
  • 39