问题
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