复制二维数组 - 仍然使用引用? [英] Copying a two dimensional array - still uses references?

查看:60
本文介绍了复制二维数组 - 仍然使用引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有(恕我直言)一个奇怪的行为.我目前正在为 Tic Tac Toe 游戏实现 minimax 算法.在我的后继"方法中,我想确定所有可能的动作.代码如下:

I have got (IMHO) a strange behaviour in my code. I am currently implementing the minimax algorithm for a Tic Tac Toe game. In my "successor" method I want to determine all possible moves. Here's the code:

private ArrayList<TicTacToeState[][]> successor(final TicTacToeState[][] field, TicTacToeState s) {
    ArrayList<TicTacToeState[][]> returnList = new ArrayList<TicTacToeState[][]>();
    for (int i = 0; i < TicTacToeGame.FIELDSIZE; i++) {
        for (int j = 0; j < TicTacToeGame.FIELDSIZE; j++) {
            if (field[i][j] == TicTacToeState.Empty) {
                TicTacToeState[][] currentCopy = new TicTacToeState[TicTacToeGame.FIELDSIZE][TicTacToeGame.FIELDSIZE];
                System.arraycopy(field, 0, currentCopy, 0, field.length);
                currentCopy[i][j] = s; // <- field seems to be referenced?!
                returnList.add(currentCopy);
            }
        }
    }
    return returnList;
}

如您所见,我想获取所有可能的移动并将它们保存到一个数组列表中.不幸的是,在currentCopy"中设置值时,字段"也发生了变化.但是该字段不应该被引用,因为我复制了数组.错误在哪里?我已经尝试在二维数组上使用 clone() 方法 -> 同样的问题.

As you can see, I want to get all possible moves and save them into an arraylist. Unfortunately, when setting the value in "currentCopy", the "field" is also changed. But the field shouldn't be refrenced, because I copied the array. Where is the mistake? I have already tried using the clone() method on the two dimensional array -> same problem.

感谢您的帮助.

(仅供参考,TicTacToeState 是一个枚举,包括Player1"、Player2"和Empty")

(FYI, TicTacToeState is an enumeration including "Player1", "Player2" and "Empty")

推荐答案

Java 使用浅拷贝.也就是说,您获得了一份副本,但这里不是您想要的.你想要一个深拷贝.尝试手动将每个元素复制到 returnList 中,看看会发生什么.

Java uses shallow copies. That is, you get a copy but it isn't what you want here. You want a deep copy. Try manually copying each element into returnList and see what happens.

解决此问题的另一种方法是进行移动,递归,然后取消移动.那么你根本不需要复制数组.

Another way to solve this is to make your move, recurse, then unmake the move. Then you don't need to copy the array at all.

这篇关于复制二维数组 - 仍然使用引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆