I have an object game of my Game.java class in my main class. I need to create a copy (game_copy) of game object such that when I make changes to the board of game_copy, the board of game does not get changed. I make this game_copy object as:
Game game_copy = new Game() ;
game_copy = game.clone() ;
But still when I make changes to the board of game_copy, the board of game gets changed as they still share a reference. How do I sort out this problem? Here are my Game and rplayer classes that I am using:
class Game implements Cloneable{
int n;
ArrayList<ArrayList<String>> board;
rplayer [] players;
int a ;
public Game(int n){
this.n=n;
players = new rplayer[2] ;
players[0]=new rplayer(this.a);
players[1]=new rplayer(this.a);
board= new ArrayList<ArrayList<String>>();
for(int p= 0 ; p < n*n ; p++){
ArrayList<String> r = new ArrayList<String>() ;
board.add(r) ;
}
}
public Game clone(){
Game gm ;
try {
gm = (Game) super.clone();
}
catch (CloneNotSupportedException e) {
System.out.println (" Cloning not allowed. " );
return null;
}
return gm
}
}
class rplayer{
int a;
public rplayer(int a){
this.a=a;
}
}
This is what I tried before trying to use .clone() method, but the idea of making a copy constructor didn't work either. Both the objects were always related.
public Game(Game g){
this.n=g.n;
this.players = new rplayer[2] ;
rplayer[] temp_players = new rplayer[2] ;
temp_players = g.players;
this.players = temp_players ;
this.board= new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> temp_board = new ArrayList<ArrayList<String>>() ;
for(int p= 0 ; p < n*n ; p++){
ArrayList<String> r = new ArrayList<String>() ;
board.add(r) ;
temp_board.add(r) ;
}
temp_board = g.board ;
board= temp_board;
}