0

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)]...]

Trashtalk
  • 331
  • 1
  • 11
  • Could you create a small text portion of what output you are expecting, and a small text portion of what you are getting? The graphic is both small and hard to understand in context. – Ben I. Jun 10 '17 at 17:22
  • Here you go Ben! – Trashtalk Jun 10 '17 at 17:32
  • Why do you want first row to start at `(0, 1)`, not `(0, 0)`, when you want other rows to start at `(1, 0)`, `(2, 0)`, ...? – Andreas Jun 10 '17 at 18:11

1 Answers1

0

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;
minus
  • 2,646
  • 15
  • 18