arraylist.forEach 中的引用成员正在修改?

Reference member being modified in arraylist.forEach?

我正在创建一个生存模拟器,我有一个 arrayListEntity 个。我正在编写一个 checkForDead() 方法,如果该成员已死亡,该方法将删除该成员。现在,我有一个很长的 for 语句来执行此操作。但是,我想使用 arrayList.forEach() 以使其更具可读性。如前所述,部分操作必须是删除它。如何在 forEach() 方法中引用被修改的成员?例如

a.forEach(a.remove(x));

其中a是列表,x是被修改的成员。我怎样才能得到 x 是什么?

checkForDead方法中的原代码:

for (int x = 0; x < a.size(); x++) {

            if (a.get(x).calories <= 0) {
                Fates.addDeathRecord(a.get(x).name, x, "starved to death");
                a.remove(x);
            }

            else if (a.get(x).hydration <= 0) {
                Fates.addDeathRecord(a.get(x).name, x, "died of thirst");
                a.remove(x);
            }

            else if (a.get(x).heat <= 0) {
                Fates.addDeathRecord(a.get(x).name, x, "froze to death");
                a.remove(x);
            }

            else if (a.get(x).heat >= 14) {
                Fates.addDeathRecord(a.get(x).name, x, "overheated");
                a.remove(x);
            }

            else if (a.get(x).moral <= Chance.randomNumber(0, 2)) {
                Fates.addDeathRecord(a.get(x).name, x, "commited suicide");
                a.remove(x);
            }

        }

    }
List<Entity> toRemove = new ArrayList<Entitys>();
for (int i=0; i<a.size(); i++){
    if (a.get(i).checkForDead()){
         toRemove.add(a.get(i));
         a.remove(i);
}
for (int i=0; i<toRemove.size(); i++){
    ..your code..
}

forEach 方法可能不适合在结构上修改正在迭代的集合。如 javadoc 中所述:

The default implementation behaves as if:

 for (T t : this)
     action.accept(t);

根据您使用的 List 实现,通过添加或删除操作集合可能会导致 ConcurrentModificationException。在这种情况下,使用传统的 Iteratorremove 可能仍然是最佳解决方案。

//keep track of index for death record
int x = 0;
for (Iterator<Entry> iter = a.iterator(); iter.hasNext(); ++x) {

        final Entry next = iter.next();
        if (next.calories <= 0) {
            Fates.addDeathRecord(next.name, x, "starved to death");
            iter.remove();
        }

        else if (next.hydration <= 0) {
            Fates.addDeathRecord(next.name, x, "died of thirst");
            iter.remove();
        }

        else if (next.heat <= 0) {
            Fates.addDeathRecord(next.name, x, "froze to death");
            iter.remove();
        }

        else if (next.heat >= 14) {
            Fates.addDeathRecord(next.name, x, "overheated");
            iter.remove();
        }

        else if (next.moral <= Chance.randomNumber(0, 2)) {
            Fates.addDeathRecord(next.name, x, "commited suicide");
            iter.remove();
        }

}

我相信您可以使用如下所示的 lambda 表达式。

a.foreach(element -> {
    // access element
    System.out.println(element.name);
    // do other stuff
});

您可能想查看 removeIf()-method,它会删除满足给定条件的所有元素。