gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:55:25 27 4
gpt4 key购买 nike

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

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

    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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com