Search code examples
javaarraylistresourcestile

Resource loading into ArrayList for tile-based game. (Java)


So i'm attempting to develop a tile-based game using eclipse, and i have run into a problem on how to load the resources from the resource folder into an ArrayList. I have a file reader that can load all of the needed files into a list, but i can't use class folders for each tile type (grass, stone, etc) because an ArrayList can only store one class type. Is there a way to load all sub-classes of the tile super-class into a single ArrayList.


Solution

  • If you have a parent class (or interface) that all of the other classes extend from, then you can simply use an ArrayList of that parent class. Just create an ArrayList of Tiles.

    List<Tile> tiles = new ArrayList<Tile>();
    
    Tile a = new GrassTile(); //GrassTile extends Tile
    Tile b = new StoneTile(); //StoneTile extends Tile
    
    tiles.add(a);
    tiles.add(b);
    
    for(Tile t : tiles){
       t.doTileStuff();
    }
    

    Edit: You could also reconsider your design and try to favor composition over inheritance. Instead of having a bunch of classes that extend Tile, have a single Tile class that contains attributes that determine how it behaves and looks.