2

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,832
  • 2
  • 13
  • 22

2 Answers2

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

You could also do this using the stream API:

objs.values().forEach(v -> v.tick());

Or even more compact:

objs.values().forEach(MyOb::tick);
Tim B
  • 40,716
  • 16
  • 83
  • 128
3
objs.forEach((k, v) -> v.tick());
Tahar Bakir
  • 716
  • 5
  • 14