title: Java Clone Class With Primitive Types
body: <p>I am trying to create a deep copy of an <code>Object</code> (called <code>State</code>) to do modifications to one of the instances within it, then follow up with code that modifies the old <code>State</code> based on the new <code>State</code>.</p>
  
  <p>Here is <code>State</code>:</p>
  
  <pre><code>public class State implements Cloneable {
  
      // 0: empty
      // 1: white
      // 2: black
      private int[][] board;
  
      private int player;
  
      public State(int[][] board, int player) {
          this.board = board;
          this.player = player;
      }
  
      public int[][] getBoard() {
          return board;
      }
  
      public int getPlayer() {
          return player;
      }
  
      public void setBoard(int[][] board) {
          this.board = board;
      }
  
      public void setPlayer(int player) {
          this.player = player;
      }
  
      @Override
      protected Object clone() throws CloneNotSupportedException {
          return super.clone();
      }
  
  }
  </code></pre>
  
  <p>Then, here is how I try and access it:</p>
  
  <pre><code>State temp = (State) s.clone();
  Action act = determineAction(temp);
  doSomething(s, act);
  </code></pre>
  
  <p><code>s</code> is a <code>State</code> passed into the method.  After <code>determineAction</code> is called, for some reason the <code>board</code> in <code>s</code> is being modified along with <code>temp</code> even though it is not passed...  How come this is?  Shouldn't the call to <code>.clone()</code> clone instances of all primitive types such that they can be uniquely modified?</p>
  
  <p>That is what this post suggests:  <a href="http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/" rel="nofollow">http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/</a></p>
  
  <p>I'm struggling to see why this wouldn't be deep copied, and why my modifications to <code>temp</code> would also modify <code>s</code>.</p>
  
  <p>Any tips would be greatly appreciated -- thanks!</p>
  
  <p>Edit - For anyone curious, here's what fixed it:</p>
  
  <pre><code>@Override
  protected Object clone() throws CloneNotSupportedException {
  
      State cloned = (State) super.clone();
  
      int[][] clonedBoard = new int[8][8];
  
      for (int i = 0; i &lt; 8; i++) {
          for (int j = 0; j &lt; 8; j++) {
              clonedBoard[i][j] = board[i][j];
          }
      }
  
      cloned.setBoard(clonedBoard);
  
      return cloned;
  }
  </code></pre>