I have a simple function that returns a specific ArrayList but I'm wondering if there is a way to return one by its type?
I have this:
ArrayList<Tile> getTiles() {
ArrayList<Tile> tiles = new ArrayList<>();
for (GameObj obj : gameObjs) {
if (obj instanceof Tile)
tiles.add((Tile) obj);
}
return tiles;
}
and this:
ArrayList<Obj> getObjs() {
ArrayList<Obj> objs = new ArrayList<>();
for (GameObj obj : gameObjs) {
if (obj instanceof Obj)
objs.add((Obj) obj);
}
return objs;
}
So I'll end up with multiple functions just to return a simple ArrayList again and again. Of course Tile, Obj etc extend GameObj. I'm wondering if there's a way to return whichever type I require. I tried this, but it doesn't work:
ArrayList<GameObj> getByType(Class<? extends GameObj> whichType) {
ArrayList<GameObj> objs = new ArrayList<>();
for (GameObj obj : gameObjs) {
if (obj.getClass() == whichType)
objs.add(obj);
}
return objs;
}
ArrayList<Tile> tiles = (ArrayList<Tile>) getByType(Tile.class);
I get the error Cannot cast from ArrayList<GameObj> to ArrayList<Tile>