1

对不起,标题不是很容易理解,但我的英语没有帮助。我是 java 的新程序员,尽管阅读了参数的工作原理,但我并不真正了解发生了什么。

sudokuBoard alter = new sudokuBoard();
this.createRandomSudokuBoard();
alter.setBoardFromArray(this.getBoard().clone());

(...) 

for(int i = 0; i < 81; i++) {
    alter.clearCell(positionListonX[i], positionListonY[i]); <<<<<<<<<<<<< Here
    if(alter.numberOfSolutions(2) < 2) {
        this.clearCell(positionListonX[i], positionListonY[i]);
        alter.setBoardFromArray(this.getBoard().clone());
    } else {
        alter.setBoardFromArray(this.getBoard().clone());
    }
}

发生的情况是,在指示的行中,调用clearCell对象的方法alter也在修改当前对象(this)。在最后一次绝望的尝试中,我尝试使用该clone()方法解决它(如您所见),但它不起作用。

这是怎么回事?我错过了什么?非常感谢你。

4

1 回答 1

1

如果您还没有实现clone()in SudokuBoard,那么您可能会得到默认clone()定义 on Object,它不会执行对象的深层复制。有关说明,请参阅Deep Copy。如果您实际上想要一个完全独立的板子实例alter,您将需要执行以下操作:

class SudokuBoard
{
    public void setBoard( SudokuBoard other )
    {
        for( int i = 0; i < 81; i++ )
        {
            this.positionListonX[i] = other.positionListonX[i];
            this.positionListonY[i] = other.positionListonY[i];
        }
        // Copy any other properties
    }
}

请注意,如果您的positionListonXpositionListonY数组中的值不是原始类型,您还需要这些的深层副本。这实际上是一个复制构造函数,但我没有给它签名 ( public SudokuBoard( SudokuBoard other)) 因为我不知道 SudokuBoard 的其余内部结构。

这将有助于查看更多在 SudokuBoard 类中定义的方法签名,因此我们知道哪些方法可用并且可以理解它们的作用。

编辑

class SudokuBoard
{
    public void setBoardFromArray( int[][] otherBoard )
    {
        for( int i = 0; i < otherBoard.length; i++ )
        {
            // Clone the arrays that actually have the data
            this.board[i] = otherBoard[i].clone();
        }
    }
}
于 2013-03-31T03:54:29.397 回答