在java中克隆和编辑int [] [] - 无法更改int [] []
这是我的代码:
public Move makeMove(int[][] board)
(...更多代码...)
int[][] nextMove = board.clone();
nextMove[i][j] = 1;
int nextMaxMove = maxMove( nextMove );
System.out.println( next max move: " + nextMaxMove + " " + maxMove( board ) );
int[][] 棋盘
是一个 8x8 棋盘,我尝试计算棋盘游戏中的最佳动作。
当我找到一系列同样好的动作时,我想检查对手给出了我可以做的不同动作的可能性。因此,我clone()
board
,编辑克隆nextMove[i][j] = 1
并调用maxMove
code> 新板上的功能。
println 用于调试,我对 maxMove( nextMove );
和 maxMove( board )
得到相同的结果,这是错误的..看起来像 nextMove
保持不变..
This is my code:
public Move makeMove(int[][] board)
(... more code ...)
int[][] nextMove = board.clone();
nextMove[i][j] = 1;
int nextMaxMove = maxMove( nextMove );
System.out.println( next max move: " + nextMaxMove + " " + maxMove( board ) );
the int[][] board
is a 8x8 board and I attempt to calculate the best move in a board game.
When I have found a list of equaly good moves I want to check what possibilities the opponent have given the different moves I can do. So I clone()
the board
, edit the clone nextMove[i][j] = 1
and call the maxMove
function on the new board.
the println is for debugging, and I get the same result for maxMove( nextMove );
and maxMove( board )
, this is wrong.. It seems like nextMove
remain unchanged..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为您的数据结构是一个数组的数组 - 在幕后,它是一个引用数组。您的克隆是浅副本,因此克隆包含原始数组。
此示例代码演示了这一点。
解决方案是显式复制二维数组的内容,而不是使用
.clone()
。This happens because your data structure is an array of arrays - which, under the hood, is an array of references. Your clone is a shallow copy, so the clone contains the original arrays.
This sample code demonstrates it.
The solution is to explicitly copy the contents of your 2-dimensional array, rather than using
.clone()
.