2

I want to perform a deep copy on an object, does the clone function work to that extent, or do I have to create a function to physically copy it, and return a pointer to it? That is, I want

Board tempBoard = board.copy();

This would copy the board object into the tempBoard, where the board object holds:

public interface Board {
    Board copy();
}

public class BoardConcrete implements Board {
    @override
    public Board copy() {
      //need to create a copy function here
    }

    private boolean isOver = false;
    private int turn;
    private int[][] map;
    public final int width, height;


}
Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
SNpn
  • 2,107
  • 6
  • 36
  • 52
  • http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying-an-instance/2156367#2156367 – Bozho Nov 01 '11 at 08:14

1 Answers1

3

The Cloneable interface and the clone() method are designed for making copies of objects. However, in order to do a deep copy, you'll have to implement clone() yourself:

public class Board {
    private boolean isOver = false;
    private int turn;
    private int[][] map;
    public final int width, height;
    @Override
    public Board clone() throws CloneNotSupportedException {
      return new Board(isOver, turn, map.clone(), width, height);
    }
    private Board(boolean isOver, int turn, int[][] map, int width, int height) {
      this.isOver = isOver;
      this.turn = turn;
      this.map = map;
      this.width = width;
      this.height = height;
    }
}
NPE
  • 464,258
  • 100
  • 912
  • 987