title: Object Clones and Knowing Underlying Object in Reference (JAVA)
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Here is my code for the successor function wrapper class:</p>
  
  <p>public class Successor {</p>
  
  <pre><code>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&lt;dim_y; i++){
          for(int j=0; j&lt;dim_x; j++){
              int neighbors = 0;
              neighbors = countThyNeighbors(i, j);
              if((neighbors&gt;3 || neighbors&lt;3) &amp;&amp; current_state[i][j]){
                  nextstate[i][j] = false;
              } else if(!current_state[i][j] &amp;&amp; neighbors&gt;=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&lt;8; i++){
          try{
          if(current_state[grid_y[i]][grid_x[i]])
              neighbors++;
          } catch(Exception e) { continue;}
      }
      return neighbors;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The get() and set() functions in the WorldPopulation class are merely assignment and return operations.</p>
  
  <p>I know a bit about nuances of cloning (deep and shallow clones) from a C# background, but I am totally new in Java paradigms.</p>
  
  <p>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</p>