i have some trouble with deep copying. I have this java project, chess, and I need to use the clone() method, because I need to try new configurations without changing the board.
Board scacchiera = new Board();
Initialization(scacchiera);
Board clone = scacchiera.clone();
System.out.println(scacchiera.toString());
System.out.println(clone.toString());
I create an object, scacchiera, then I clone it. I think I have done correctly a deep copy, but when I change something in scacchiera, clone changes too. In object Board:
public class Board implements Cloneable{
//TODO
//rivedere se check e checkmate public o private;
//se private, costruire get e set;
public Pedine[][] board;
public boolean check;
public boolean checkmate;
//creating 2 lists for all the pieces; Neri=black, Bianchi=White
public ArrayList<Pedine> Neri;
public ArrayList<Pedine> Bianchi;
public Board(){
this.board = new Pedine [8][8];
this.check = false;
this.checkmate = false;
this.Neri = new ArrayList<Pedine>();
this.Bianchi = new ArrayList<Pedine>();
}
...
@Override
public Board clone() throws CloneNotSupportedException{
Board cloned = (Board) super.clone();
cloned.board = (Pedine[][]) board.clone();
return cloned;
}
I have this double array of Pedine, and I have to clone it too, so I do:
public class Pedine implements Cloneable{
private int x;
private int y;
private Piece pezzo;
private Colour colore;
...
@Override
public Pedine clone() throws CloneNotSupportedException{
return (Pedine) super.clone();
}
Why it doesn't work?
I tried this code too, but it doesn't work.
@Override
public Board clone() throws CloneNotSupportedException{
Board cloned = (Board) super.clone();
cloned.board = (Pedine[][]) board.clone();
for (int i=0; i<8; i++)
for(int j=0; j<8; j++){
cloned.board[i][j] = board[i][j].clone();
}
return cloned;
}
(Pedine extends Object)