gpt4 book ai didi

使用正确的remove()方法时显示java.util.ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-01 16:42:24 24 4
gpt4 key购买 nike

当 isActive 为 false 时,我尝试删除实体。当实体属性 isActive 设置为 false 时,它​​会进入 if 语句并删除该实体,之后再次迭代实体列表时,然后崩溃。根据我的研究,我正在使用正确的方法从数组列表中删除对象。

删除实体并迭代列表时的代码是

    for (Entity entity : entities) {// itaarate through all the entities in list of entities

entity.render(shader, camera, this);// render each entity

if (!entity.isActive())// checks if entity attribute is active
entities.remove(entity);// removes entity from list

}

当使用调试器从列表中删除实体后,它会返回到 for 循环的顶部,然后显示此页面

enter image description here

调试时的变量窗口

enter image description here

控制台中显示的完整错误是

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at project.World.render(World.java:196)
at project.Main.<init>(Main.java:152)
at project.Main.main(Main.java:167)

正在创建的列表是

public static ArrayList<Entity> entities; // contains all entities

最佳答案

java.util.ConcurrentModificationException displaying when using the correct remove() method

其实,你用错了方法。或者更准确地说,是错误对象上的 remove() 方法。

您可以在迭代时删除元素...但您需要在 Iterator 对象上使用 remove() 方法;请参阅javadoc了解更多详情。

Iterator<Entity> it = entities.iterator();
while (it.hasNext()) {
Entity entity = it.next();
entity.render(shader, camera, this);

if (!entity.isActive()) {
it.remove();
}
}

请注意,Iterator.remove() 是一个可选操作,但 ArrayList 迭代器确实实现了它。

ListIterator API 具有相同的方法,但 Iterator 更通用。 (您可以将上述示例代码与任何可以使用 Iterator 进行迭代的类型一起使用,而不仅仅是 List 类型。)

关于使用正确的remove()方法时显示java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60831777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com