0

Hey people i have this structure for the search tree

class State
{
    //CLASS STATE
    int value;
    char[][] state; //the game Grid 
    State child[]; // children of current state, maximum is 8
    State(char[][] src)
    {
        state=src;
        child=new State[8];
    }

this is the root node definition

 State rootNode = new State(currentGrid);
 rootNode.value=-1;
 int v =maxValue(rootNode,depth);

after the end of recursion in the max value function the array in rootNode should not be edited since its the the first state but when i Display it i get an array filled with stuff which means that the rootNode.state passed by reference to the max value function :(

//i am trying to implement MiniMax Algorithm.

Faris
  • 875
  • 1
  • 9
  • 18

3 Answers3

2

If you don't want objects that are passed as parameters to be changed, pass in a copy (or make a copy of the parameter inside the method).

Note that char[][] means you have an array of char arrays, i.e. you are working with objects and if you copy the first level you still might have a reference to the second.

Thus you might have to loop through the first level/dimension and copy all the arrays in there, like this:

char target[][] = new char[state.length][0];

for( int i = 0; i < state.length; ++i ) { 
  target[i] = Arrays.copyOf(state[i], state[i].length);
}
Thomas
  • 87,414
  • 12
  • 119
  • 157
1

If you need, you can easily create a copy of the array through Arrays.copyOf

You can also create a deep copy. How to do this has been answered here: How to deep copy an irregular 2D array

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
1

Yes, Java passes references to arrays and not the array as a value. So if you give a reference to your internal state away, the receiver can change it and the change is "visible" in the source (in fact: it's only one array that has been changed and all reference holders will see the change).

Quick fix/solution: clone your state array and pass a reference to this clone instead of the original. This will keep your internal root state unmodified.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • 1
    @aioobe - cloning will do whatever you do in your cloneing algorithm (and, BTW - a shallow copy might be sufficient in his case, looks like he's just moving around objects in the array, like chess figures) – Andreas Dolk May 05 '11 at 10:53