2

オブジェクトに対してディープコピーを実行したいのですが、clone関数はその程度まで機能しますか、それとも物理的にコピーしてそのオブジェクトへのポインターを返す関数を作成する必要がありますか?つまり、私は欲しい

Board tempBoard = board.copy();

これにより、ボードオブジェクトがtempBoardにコピーされ、ボードオブジェクトが保持されます。

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;


}
4

1 に答える 1

3

Cloneableインターフェイスとメソッドは、オブジェクトのclone()コピーを作成するために設計されています。ただし、ディープ コピーを行うには、clone()自分で実装する必要があります。

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;
    }
}
于 2011-10-09T09:11:40.920 に答える