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;


}
1

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.