I am currently trying to create an entity based system for a game in Java with a handler class for updating and solving interaction between entities of different subclasses. They can damage each other as to remove oneanother and spawn in more entities with methods in their respective class while all still inheriting from the Entity superclass. Here is a summarized code as for my problem to demonstrate the issue:
The Entity class:
public class Entity {
Manager manager;
public Entity(Manager manager) {
this.manager = manager;
}
public void update() {
switch ((int) (Math.random()*3)){
case 1:
this.add();
case 2:
this.remove();
}
}
public void add() {
this.manager.addNew();
}
public void remove() {
this.manager.removeRandom();
}
}
The Manager class
import java.util.ArrayList;
public class Manager {
ArrayList<Entity> entities;
public Manager() {
this.entities = new ArrayList<>();
}
public void update() {
for (Entity e :
entities) {
e.update();
}
}
public void addNew() {
entities.add(new Entity(this));
}
public void removeRandom() {
entities.remove((int) (Math.random()* entities.size()));
}
public ArrayList<Entity> getEntities() {
return entities;
}
}
And lastly the main method:
public class ModifyWhileIterating {
public static void main(String[] args) {
Manager manager = new Manager();
for (int i = 0; i < 10; i++) {
manager.addNew();
}
for (Entity e :
manager.getEntities()) {
e.update();
}
}
}
I’ve tried using iterators (which also results in a ConcurrentModificationException error) and do acknowledge the fact that I can use a RemoveIf method to first update all entities and then remove them if they meet a certain predicate criteria. I’m mostly posting this to see if anyone has a more elegant and simple solution as to remain readable, reliable and to declutter flow. To summarize a certain class or object (maybe an IList or Collection could work however I’ve not found a fitting solution to others’ questions) that could iterate through a list while modifying (adding and removing) element at the same time is what I’m looking for or some functional way as to update all entities.
Calle Jonasson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.