Reputation: 365
Sorry, the title is not very understandable, but my English is not helping. I am a new programmer in java, and despite having read how parameters work, I do not really understand what is happening.
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());
}
}
What happens is that in the indicated line, calling the method clearCell
of the object alter
is also modifying the current object (this). In a last desperate attempt, I tried to resolve it with the clone()
method (as you can see), but it did not work.
What's going on? What am I missing? thank you very much.
Upvotes: 1
Views: 62
Reputation: 688
If you haven't implemented clone()
in SudokuBoard
, then you're probably getting the default clone()
defined on Object
, which doesn't perform a deep copy of the object. See Deep Copy for an explanation. If you actually want a completely separate instance of your board in alter
, you will need to do something like this:
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
}
}
Note that if the values in your positionListonX
and positionListonY
arrays are not primitive types, you'll also need deep copies of those. This is effectively a copy constructor, but I didn't give it that signature (public SudokuBoard( SudokuBoard other)
) because I don't know the rest of the internals of SudokuBoard.
It would help to see more of the method signatures defined in your SudokuBoard class, so we know what methods are available and can understand what they do.
Edit
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();
}
}
}
Upvotes: 1