Java 使用原始类型克隆 Class

Java Clone Class With Primitive Types

我正在尝试创建一个 Object 的深层副本(称为 State)以对其中的一个实例进行修改,然后跟进修改旧 State 基于新的 State.

这里是State:

public class State implements Cloneable {

    // 0: empty
    // 1: white
    // 2: black
    private int[][] board;

    private int player;

    public State(int[][] board, int player) {
        this.board = board;
        this.player = player;
    }

    public int[][] getBoard() {
        return board;
    }

    public int getPlayer() {
        return player;
    }

    public void setBoard(int[][] board) {
        this.board = board;
    }

    public void setPlayer(int player) {
        this.player = player;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

然后,这是我尝试访问它的方式:

State temp = (State) s.clone();
Action act = determineAction(temp);
doSomething(s, act);

s 是传递给方法的 State。在调用 determineAction 之后,由于某种原因 s 中的 boardtemp 一起被修改,即使它没有通过......这是怎么回事?不应该调用 .clone() 克隆所有基本类型的实例,以便可以唯一地修改它们吗?

这就是这个 post 的建议:http://howtodoinjava.com/core-java/cloning/a-guide-to-object-cloning-in-java/

我正在努力了解为什么这不会被深度复制,以及为什么我对 temp 的修改也会修改 s.

任何提示将不胜感激 -- 谢谢!

编辑 - 对于任何好奇的人,修复它的方法如下:

@Override
protected Object clone() throws CloneNotSupportedException {

    State cloned = (State) super.clone();

    int[][] clonedBoard = new int[8][8];

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            clonedBoard[i][j] = board[i][j];
        }
    }

    cloned.setBoard(clonedBoard);

    return cloned;
}

super.clone() 不进行深层复制,int[][] 不是原始类型。

它适用于 int player,因为它是原始类型,一个简单的副本(由 Object#clone 完成)就足够了。

您需要自己(深度)复制您的 int[][]

原始数据类型的深度克隆。您也可以使用序列化实现深度克隆