在java中复制对象

时间:2011-10-09 09:08:21

标签: java cloning

我想对一个对象执行深层复制,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;


}

1 个答案:

答案 0 :(得分: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;
    }
}