gpt4 book ai didi

java - 无法添加到 ArrayList

转载 作者:太空宇宙 更新时间:2023-11-04 11:59:46 24 4
gpt4 key购买 nike

我正在尝试迭代列表“breadthBoard”,并向其中添加一个数组“board”。但是,我添加到数组中的每个数组都会以某种方式变成原始数组,然后即使我已经测试了数组已更改,该数组也会被复制。

neighbourNodes 是一个列表,其中包含板上与当前节点相邻的所有值。

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');

}

}

最佳答案

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

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

关于java - 无法添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41027734/

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