I'm a bit confused regarding recursion in Java:
public int recursion(Board board2,int x){
Board board1 = board2;
if(x==3){
System.out.println("End");
return 0;
}
board1.fix(obj, Color.BLUE, x, 12);
return recursion(board1, x+1);
}
This is just an example of putting an object inside a board. How can I make changes to board1
, but not to the original board that I passed in as a parameter? Since outside the method, the Board
that I passed as parameter is changed after the execution, and I don't understand why. I was reading that Java passes by value and not by reference. I want to make the program return to its previous state during the recursion and not change the real board.
EDIT
I tried it this way, but it still doesn't work:
public int recursion(Board board2,int x){
try{
board1 = (Board)board2.clone();
}catch (Exception e){
System.out.println("Error "+e);
}
if(x==3){
System.out.println("End");
return 0;
}
board1.fix(obj, Color.BLUE, x, 12);
return recursion(board1, x+1);
}
EDIT 2
Here's how I implemented the clone method
class Board extends JPanel implements Cloneable{
// ...
@Override
protected Board clone() throws CloneNotSupportedException{
return(Board) super.clone();
}
// ...
EDIT 3
I still can't get it to work
class Board extends JPanel implements Cloneable{
public Color[][] board;
@Override
public Board clone(){
Board board1 = new Board();
board1.board = this.board;
return board1;
}
// ...
}