我目前正在尝试为 Java 游戏创建一个基于实体的系统,其中包含一个处理程序类,用于更新和解决不同子类的实体之间的交互。它们可以互相损害,从而删除彼此并使用各自类中的方法生成更多实体,同时所有实体仍然继承自实体超类。这是针对我的问题的总结代码,用于演示该问题:
实体类:
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();
}
}
经理班
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;
}
}
最后是主要方法:
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();
}
}
}
我尝试使用迭代器(这也会导致 ConcurrentModificationException 错误),并且承认我可以使用 RemoveIf 方法首先更新所有实体,然后在它们满足特定谓词条件时删除它们。我发布这篇文章主要是为了看看是否有人有一个更优雅和简单的解决方案来保持可读性、可靠性和整理流程。总结某个类或对象(也许 IList 或 Collection 可以工作,但我还没有找到其他人问题的合适解决方案),它们可以在修改(添加和删除)元素的同时迭代列表,这就是我的想法正在寻找某种功能性方法来更新所有实体。
我会考虑将您的更新分为两步。添加一个
pendingUpdates
队列,描述您希望执行的操作(添加实体、删除实体等)。您的管理器 add
和 remove
方法将添加到此队列,而不是直接添加到 entites
列表。迭代完成后,连续将每个 pendingUpdates
出队并将它们应用到 entities
列表。