2

我想对一个对象执行深层复制,该clone函数是否工作到那个程度,还是我必须创建一个函数来物理复制它,并返回一个指向它的指针?也就是说,我要

Board tempBoard = board.copy();

这会将 board 对象复制到 board 对象所在的 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 回答