Search code examples
javafor-loopmultidimensional-arraynested-loops

How to stop for loops from overwritng variables in nested ArrayLists


Recently I've been slamming by head against this piece of code:

    for(int i = 0; i < cols; i++) {
        for(int j = 0; j < rows; j++) {
            SqrTileNormal temp = new SqrTileNormal(i, j, this, ID.Tile);
            setTile(temp);
        }
    }

//additional info
public void setTile(Tile tile) {
    int xPosGrid = tile.getXPosGrid();
    int yPosGrid = tile.getYPosGrid();
    System.out.println("Coords: (" + xPosGrid + ", " + yPosGrid + ")");
    this.tiles.get(xPosGrid).set(yPosGrid, tile);
}

//how the nested array looks like.
protected List<ArrayList<Tile>> tiles;

It's part of a constructor which is supposed to fill a two-dimensional array with SqrTileNormal. I have found what the issue is: Every iteration of the for loop keeps rewriting the previous iterations, so they all end up whit the same xPosGrid and you see this: All the tiles are on one side

I have been trying some things but I usually keep the overwriting issue and I don't want to make it unnecessarily complicated and long. Does anyone know of a solution to this problem? Any help would be appreciated!

Edit:

What I had: [[null, null, null...][null, null, null...][(null, null, null...]

What I want:

What I get: [[(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)]...]


Solution

  • The problem is in how you initialize this.tiles, you are not showing how you do it but possibly you are setting just 1 array list, so in fact you have ten times the same value list.

    Your this.tiles init should look like:

    private static List<List<Tile>> getListOfLists() {
        int numcol = 5;
        int numrow = 5;
    
        List<List<Tile>> bidiArray = new ArrayList<>();
        for (int i = 0; i < numcol; i++) {
            List<String> sublist = new ArrayList<>();
            bidiArray.add(sublist);
            for (int j = 0; j < numrow; j++) {
                sublist.add(null);
            }
        }
        return bidiArray;
    }
    

    But in fact, dealing with a fixed number of columns and rows I would rather use arrays such as :

    Tile[][] bidiArray = new Tile[numcol][numrow];
    

    And then set it like this:

      this.tiles[xPosGrid][yPosGrid]= tile;