Copying a two dimensional array - still uses references?

萝らか妹 提交于 2019-12-13 21:29:29

问题


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;
}

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.

Thank you for any help.

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


回答1:


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.




回答2:


You are using a a 2 dimensional array but only copying the first dimension of the array in your system array copy. I would suggest not doing all that copying though. Use something else to describe the possible moves perhaps. Note also that you are not copying the contents of the array, only the array.



来源:https://stackoverflow.com/questions/10269018/copying-a-two-dimensional-array-still-uses-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!