Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Recursion and Passing by value

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;  
    }
    // ...
}   
like image 484
GioGio Avatar asked Jun 03 '26 18:06

GioGio


1 Answers

In the method, the parameter board2 holds the same reference as the argument you passed into the method. And I guess you don't want it to be this way. You want a copy of the board with the same values but different references, so that the effects you make on the copy does not affect the argument you passed in. Am I right? (I can read your mind!)

The clone() method is the best to use in this situation! First, in the Board class, implement Cloneable.

public class Board implements Cloneable {

}

And then add the clone() method to it.

The implementation of it is roughly this:

  1. Create a new instance of the class

  2. Assign all the fields found in this to the new instance

  3. return the new instance.

like image 143
Sweeper Avatar answered Jun 06 '26 07:06

Sweeper