Search code examples
javaarraysarraylistlibgdx

How can I create a two-dimensional array containing ArrayLists?


How can I create a two-dimensional array containing ArrayLists? Something like this :

ArrayList<Character>[][] myArray = new ArrayList<Character>[][];

and would it be ok to do the following :

I need to compare the position of some characters with the position of the buildings in my map. Several buildings can belong to the same tile, but one can be drawn in front of the character and the other behind him. This comparison has to be done all the time in the game, with every character.

I am trying to update an array of characters each time a character is moving from one tile to another. Then the render method should look for how many characters, if any, are in a specific tile, and loop over the characters in this tile to draw them in front or behind the buildings.

Something like this :

//init
ArrayList<Character>[][] arrayOfCharacters = new ArrayList<Character>[][];

//each tile in the map
for (int y = 0; y < 9; y++){
    for(int x = 9-1; x >= 0; x--){
        if ( arrayOfCharacters[y][x].length > 0 ){
            for ( int i=0, i< arrayOfCharacters[y][x].length; i++ ){
                //compare which building is in front or behind the characters
                //then
                characterInThisTile = index of each character in arrayOfCharacters[y][x] 
                spriteBatch.draw(characterInThisTile, x_pos, y_pos, tileWidth, tileHeight);
            }   
        }

    }
}

Solution

  • ArrayList<Character>[][] arrayOfCharacters = new ArrayList[9][9];
    for(int i=0;i<arrayOfCharacters.length;i++){
          for(int i2=0;i2<arrayOfCharacters[i].length;i2++){
                arrayOfCharacters[i][i2]=new ArrayList<Character>(20);
          }
    }