在Java中复制包含对象的双ArrayList(ArrayList <arraylist <object>&gt;&gt;)</arraylist <object>

时间:2015-03-02 14:46:25

标签: java function loops object arraylist

好的,所以我之前发布了一个帖子,回答了很多我的问题并帮助我改进了我的代码。但是,我遇到了另一个问题,好吧,我不知道为什么,但我想也许副本只是指向原始对象..(虽然我尽力避免这种情况)

在我的游戏代码中,我有这个:

    public void undo(){
    if (condition.size() > 0){
        board = condition.pop();
    }
}

public ArrayList<ArrayList<Cell>> copyBoard(ArrayList<ArrayList<Cell>> board){
    ArrayList<Cell> copiedArray = new ArrayList<Cell>();
    ArrayList<ArrayList<Cell>> copiedBoard = new ArrayList<ArrayList<Cell>>();

    for (ArrayList<Cell> array : board) {
        for (Cell cell : array){
            Cell copiedCell = new Cell(cell);
            copiedArray.add(copiedCell);
        }
        copiedBoard.add(array);
    }
    return copiedBoard;
}

在我的Cell代码中,我有这个构造函数用于复制其他单元格:

    String symbol = " ";
boolean isAHole = false;

public Cell (Cell another){
    this.symbol = another.symbol;
    this.isAHole = another.isAHole;
}

在程序中我使用它来管理包含不同条件的堆栈(我希望能够撤消)

                if (!command.equals("undo")){
                    game.condition.push(game.copyBoard(game.board));
                }
                if (command.equals("undo")){
                    game.undo();
                }

但每当我尝试撤消一个动作时,会弹出一个元素,但条件保持不变。 (董事会没有改变)

你有什么想法吗?

致以最诚挚的问候,并提前感谢您的帮助

3 个答案:

答案 0 :(得分:1)

您的阵列副本有两个问题:

1-您只复制新数组中的第一行单元格,但是对于其他行,您继续将另一行中的单元格添加到相同的数组中。解决方案是将new ArrayList<Cell>移到第一个for

2-复制单元格后,添加原始数组而不是复制的数组。

抄板得到纠正:

public ArrayList<ArrayList<Cell>> copyBoard(ArrayList<ArrayList<Cell>> board){
    ArrayList<ArrayList<Cell>> copiedBoard = new ArrayList<ArrayList<Cell>>();

    for (ArrayList<Cell> array : board) {
        ArrayList<Cell> copiedArray = new ArrayList<Cell>();
        for (Cell cell : array){
            Cell copiedCell = new Cell(cell);
            copiedArray.add(copiedCell);
        }
        copiedBoard.add(coppiedArray);
    }
    return copiedBoard;
}

答案 1 :(得分:1)

您应该在每次迭代中初始化arrayList复制的Array,并添加它而不是原始的:

public ArrayList<ArrayList<Cell>> copyBoard(ArrayList<ArrayList<Cell>> board){

    ArrayList<ArrayList<Cell>> copiedBoard = new ArrayList<ArrayList<Cell>>();

    for (ArrayList<Cell> array : board) {
        ArrayList<Cell> copiedArray = new ArrayList<Cell>();
        for (Cell cell : array){
            Cell copiedCell = new Cell(cell);
            copiedArray.add(copiedCell);
        }
        copiedBoard.add(copiedArray);
    }
    return copiedBoard;
}

答案 2 :(得分:0)

我认为你应该在第一个循环中移动copiedArray

public ArrayList<ArrayList<Cell>> copyBoard(ArrayList<ArrayList<Cell>> board){    
    ArrayList<ArrayList<Cell>> copiedBoard = new   ArrayList<ArrayList<Cell>>();

    for (ArrayList<Cell> array : board) {
        //move it here
        ArrayList<Cell> copiedArray = new ArrayList<Cell>();
        for (Cell cell : array){
            Cell copiedCell = new Cell(cell);
            copiedArray.add(copiedCell);
        }
        copiedBoard.add(copiedArray);
    }
    return copiedBoard;
}