Objects in List have the same value - that of the last element added [duplicate]

别来无恙 提交于 2020-06-17 04:19:32

问题


Hy,

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?

Here is the code:

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

At the end the walls variable will hold the last result of wall at multiple times.

Thanks for the help!


回答1:


You always change the same object:

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



回答2:


You need to know that array is an object. When you declare a variable, you are declaring a reference to that array.

That means, you are simply referring the same array and adding the same array multiple times to your walls

You should create a new array for every entry in walls



来源:https://stackoverflow.com/questions/26356521/objects-in-list-have-the-same-value-that-of-the-last-element-added

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!