列表中的对象具有相同的值-最后添加的元素的值相同 [英] Objects in List have the same value - that of the last element added
问题描述
我对JAVA有点陌生,并且遇到了很大的问题.当我将元素添加到List<int[]>
时,结果将是一个具有相同值的充满列表.
为什么JAVA会这样工作?
I'm a bit new to JAVA, and having a big problem. While I'm adding elements to a List<int[]>
the result will be a List full of with the same value.
Why JAVA is working like this?
这是代码:
// Global variables
private static int rows = 20;
private static int columns = 30;
private static String[][] labirinth = new String[rows][columns];
private static List<int[]> walls = new ArrayList<int[]>();
// Local variables inside a function
int[] wall = new int[2];
if(row - 1 <= rows && labirinth[row-1][column] == "*")
{
wall[0] = row-1;
wall[1] = column;
walls.add(wall);
}
if(row + 1 <= rows && labirinth[row+1][column] == "*")
{
wall[0] = row+1;
wall[1] = column;
walls.add(wall);
}
if(column - 1 <= columns && labirinth[row][column-1] == "*")
{
wall[0] = row;
wall[1] = column-1;
walls.add(wall);
}
if(column + 1 <= columns && labirinth[row][column+1] == "*")
{
wall[0] = row;
wall[1] = column+1;
walls.add(wall);
}
最后,walls
变量将多次保存wall
的最后结果.
At the end the walls
variable will hold the last result of wall
at multiple times.
感谢您的帮助!
推荐答案
您始终更改同一对象:
int[] wall = new int[2];
但是每次在将新值设置到墙并将其添加到列表之前,您应该:
but each time before you set the new values to the wall and add it to the list you should:
wall = new int[2];
如果不这样做,则每次都将更改相同的墙坐标,最后只剩下一面墙,墙将具有您最后设置的坐标.
If you do not, you will just change the same wall coordinates every time and end up with just one wall which will have the coordinates that you set last.
// Local variables inside a function
int[] wall = null;
if(row - 1 <= rows && labirinth[row-1][column] == "*")
{
wall = new int[2];
wall[0] = row-1;
wall[1] = column;
walls.add(wall);
}
if(row + 1 <= rows && labirinth[row+1][column] == "*")
{
wall = new int[2];
wall[0] = row+1;
wall[1] = column;
walls.add(wall);
}
...
这篇关于列表中的对象具有相同的值-最后添加的元素的值相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!