Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate only over specific kind of elements?

Tags:

java

oop

I have an array list as such:

private List<GameObject> gameObjects = new CopyOnWriteArrayList<GameObject>();

GameObject can be one of 3 classes: Spaceship, Beam and Asteroid. They all are similar so I keep them in one array. However spaceships have addition method shoot which is used every 100ms in other thread (which is called ShootRunnable). So I would like to iterate in it only over Spaceship because other doesnt implement shoot method. What is the best way to achieve this?

for (GameObject ob : gameObjects) {
  if (ob instanceof Spaceship) {
    ob.shoot();
  }
}

Can I iterate over it using something like the above? Just with the use of a cast or something? Please help.

like image 763
Michał Tabor Avatar asked Oct 06 '22 07:10

Michał Tabor


2 Answers

The path you're on is technically feasible, though a good rule of thumb is that if you start using reflection, you're probably doing something wrong. In this case, it might be wisest to have a two collections, one for all your game types, and one specifically for spaceships.

like image 64
Will Avatar answered Oct 11 '22 07:10

Will


In your game, are there any other actions that happen periodically?

If so, you could change the shoot() method into an abstract method (could be named periodicAction()) and place it in the GameObject class. The Spaceship class would implement this method by shooting, the other class with its specific periodic behavior and the Asteroid class by doing nothing.

like image 39
prasopes Avatar answered Oct 11 '22 07:10

prasopes