0

I'm trying to make a little 2D game / game engine in Java.

Each type of object which is the scene extends the class "Object" which has an abstract method "tick()". Furthermore there's a class called "Scene" which has a HashMap containing all the objects in the scene. I want the scene to call the method "tick()" of every object in the HashMap (60 times per second).

public class Scene {
  private HashMap<String, Object> objs; //HashMap containing all the objects

  private void tick() {
    for(Entry<String, Object> e : objs.entrySet()) {
      Object o = e.value();
      o.tick();
    }
  }

  [...]
}

Now I'm wondering if there is a better, more elegant way to achieve this. Maybe by creating an EventObject & EventListener or by using an Observable and make each object an Observer?

Marvin
  • 1,582
  • 1
  • 12
  • 19

2 Answers2

2
for (MyOb o: objs.values()) {
    o.tick();
}

You could also do this using the stream API in Java 8:

objs.values().forEach(v -> v.tick());
Tim B
  • 39,784
  • 16
  • 75
  • 127
2
objs.forEach((k, v) -> v.tick());
Tahar Bakir
  • 696
  • 5
  • 13