无法添加到ArrayList

时间:2016-12-07 21:30:40

标签: java arrays list arraylist

我试图遍历列表,' breadthBoard',并为其添加一个数组,' board'。但是,我添加到数组中的每个数组都会以某种方式变成原始数组,然后复制,即使我已经测试过数组已被更改。

neighbourNodes是一个列表,其中包含与电路板上currentNode相邻的所有值。

public List breadthBoard(List neighbourNodes, int [] currentNode, int [][] board)
{

    int x = currentNode[0] - 1; 
    int y = currentNode[1] - 1;
    //create lists
    List breadthBoard = new ArrayList();

for (int i=0; i<3;i++)
        {
            for(int j=0; j<3;j++)
            {

                if (neighbourNodes.contains(board[i][j]))
                {
                    // the temp variables allow me to switch the values then switch back later on
                    int temp = board[i][j];
                    int temp2 = board[x][y];
                    //initial switch
                    board[i][j] = temp2;
                    board[x][y] = temp;// at this point I get a successful swap but it isn't getting added to the breadth board
                    breadthBoard.add(board);

                    //test to see if I get the right results which I do
                    System.out.println("what's being added into breadth board (should be swapped)" + Arrays.deepToString(board)); 
                    System.out.println('\n');

                    switching the values back to the original postions
                    board[i][j] = temp;
                    board[x][y] = temp2;
                    System.out.print("back to normal " + Arrays.deepToString(board));// another test passed
                    System.out.println('\n');

                } 

            }

2 个答案:

答案 0 :(得分:0)

您需要制作一个制作board深层副本的方法。 clone只能制作浅层副本。

我建议在一个类中包含该板,该类具有swap方法,只需返回一个新板:

class Board {
    private final int[][] board;

    public Board(Board other) {
        this.board = new int[other.board.length][];
        for(int i = 0; i < board.length; i++) {
            board[i] = Arrays.copyOf(other.board[i], other.board[i].length);
        }
    }

    public Board swap(int i, int j, int x, int y) {
        Board result = new Board(this); // copy this board

        // swap elements    
        result.board[i][j] = board[x][y];
        result.board[x][y] = board[i][j];

        return result;
    }

    ...

}
// in the loops
breadthBoard.add(board.swap(i, j, x, y));

答案 1 :(得分:0)

我做了一些测试。 实际上,clone()使用基本类型数组进行深度复制,但它与基本二维数组的工作方式不同。
对于具有两个维度的数组,您应该迭代第一维并在第二维的clone()数组上执行int[]

   board[i][j] = temp2;
   board[x][y] = temp;

   //Here, I suppose that the second dimension has always the same size. 
   int[][] clonedBoard = new int[board[0].length][board[1].length];

   for (int t = 0; t < board.length; t++) {
     clonedBoard[t] = board[t].clone();
   }
   breadthBoard.add(clonedBoard);