java - 在 Java 中复制包含对象的双 ArrayList (ArrayList<ArrayList<Object>>>)

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

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

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

但是每当我尝试撤消一项操作时,就会从堆栈中弹出一个元素,但条件保持不变。 (董事会不变)

你有什么想法吗?

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

最佳答案

您的数组副本有 2 个问题:

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

关于java - 在 Java 中复制包含对象的双 ArrayList (ArrayList<ArrayList<Object>>>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812572/

相关文章:

java - 如何修复将使用 JNI 传输到 Java 的二维数组代码?

java - 每次我获取 pdf 文件时,我的 ArrayAdapter 堆栈

c - 数组在void函数里改了,外面还是改了!为什么? (范围)

r - 在 R 中为启动功能添加进度条

loops - Elasticsearch 遍历两个索引的值

java - 如何使用多个输入运行相同的测试?

java - Activity/App 进入后台 60 秒后调用方法

swift - 是什么让 Swift 中的调用变得昂贵?

python - 如果它的键存储在变量中,如何获取字典中的值?

python - 要求用户提供输入,直到他们给出有效的答复