2

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.

2
  • 1
    One list or more lists doesn't matter. What you should consider doing is assigning an identifier to each of the objects and store it in a Map implementation for easy retrieval. Commented Dec 20, 2014 at 5:18
  • 1
    I suggest you put the method doSomething() in GameObject (perhaps abstract) then you can just call o.doSomething() and let the instance decide what that is. Or maybe update()? Commented Dec 20, 2014 at 5:25

1 Answer 1

6

The normal way to do this would be to use an interface on GameObject.

public interface GameObject {
   void update();
}

Then just have each object implement GameObject.

public class Player implements GameObject {
   public void update() { // update player...
}

public class Wall implements GameObject {
   public void update() { // probably do nothing...
}

public class Enemy implements GameObject {
   public void update() { // update enemy...
}

Then your update loop looks like this.

public void update() {
    for(GameObject o : objects) {
       o.update();
    }
}

I can't guarantee you this is faster, but it probably is. The compiler will likely be able to optimize a virtual call like this (virtual calls are common in Object Oriented programming, so it's a really good thing for the compiler to know how to optimize), whereas I don't think it's going to be able to optimize an explicit check of the the instance class type nearly as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.