I am coding a game and have an abstract class known as GameObject and three classes extending it (Player, Wall, and Enemy).
I have a list defined as so containing all the objects in my game.
List<GameObject> objects;
When I need to do something with on of the objects, this is how I would do it:
public void update() {
for(GameObject o : objects) {
if(o instanceof Wall) {
// do something
}
else if(o instanceof Player) {
// do something
}
else if(o instanceof Enemy) {
// do something
}
}
}
So as you can see, I have to go through the whole list and check types to find just to find a single object. This seems to me like it's not very efficient. So I then thought about storing the different derived classes in their own lists.
private List<Wall> walls;
private List<Enemy> enemies;
private Player player; // only one
Would this be more efficient rather than going through the whole list containing everything and checking it's type to decide wether or not to do something? Thanks so much.
Mapimplementation for easy retrieval.doSomething()inGameObject(perhapsabstract) then you can just callo.doSomething()and let the instance decide what that is. Or maybeupdate()?