Search code examples
javaobjectreferenceclone

Object Clones and Knowing Underlying Object in Reference (JAVA)


I am trying to write source based on the "Game Of Life" simulation concept. What I did was create a class to represent the game environment state but separated the logic of the successor function in a different class. The state of the game is saved in a simple multidimensional array of booleans.

What the successor function is supposed to do is save the current state in a new array as a clone of the original and use this as basis throughout the process. It then takes the current state of the game as a reference and modifies this using the game logic. My problem is that I cloned the original into a new variable, but even this clone gets modified by the successor function.

I'm not so sure what's happening so I can't debug properly. I'm more accustomed to C#'s handling of primitive types clones.

Here is my code for the successor function wrapper class:

public class Successor {

boolean[][] current_state;
public void next(WorldPopulation worldState){
    int dim_x = worldState.get_width();
    int dim_y = worldState.get_height();
    boolean[][] nextstate = worldState.get_state();
    current_state = worldState.get_state().clone();
    for(int i=0; i<dim_y; i++){
        for(int j=0; j<dim_x; j++){
            int neighbors = 0;
            neighbors = countThyNeighbors(i, j);
            if((neighbors>3 || neighbors<3) && current_state[i][j]){
                nextstate[i][j] = false;
            } else if(!current_state[i][j] && neighbors>=3) { nextstate[i][j] = true; }
        }
    }
}
private int countThyNeighbors(int y, int x) {
    int[] grid_x = { x-1, x, x+1, x-1, x+1, x-1, x, x+1};
    int[] grid_y = { y-1, y-1, y-1, y, y, y+1, y+1, y+1};
    int neighbors = 0;
    for(int i=0; i<8; i++){
        try{
        if(current_state[grid_y[i]][grid_x[i]])
            neighbors++;
        } catch(Exception e) { continue;}
    }
    return neighbors;
}

}

The get() and set() functions in the WorldPopulation class are merely assignment and return operations.

I know a bit about nuances of cloning (deep and shallow clones) from a C# background, but I am totally new in Java paradigms.

Any suggestions to improve my code is much appreciated, but I want to know what's happening and what I'm doing wrong. Thank you very much! :D


Solution

  • Multi-dimensional arrays are represented as arrays of arrays. A clone method in Java is shallow. that means multidimentional array is not cloned deeply.

    You can implement your own deep copy method or use serialization as descibed here