问题描述
我有一个 ClassA,它有一个静态的对象 ArrayList
I have ClassA which has a static ArrayList of Objects
public static ArrayList<Meteorit> meteorits = new ArrayList<Meteorit>();
现在我想从这个列表中删除一个对象
Now I want to remove an object from this list like this
ClassA.meteorits.remove(this);
这是用 Meteorit 类编写的.但是当我想使用 ArrayList 中的对象时它会抛出异常.
This is written in Meteorit class . But it throws exception when I want to use the objects in the ArrayList .
Exception in thread "LWJGL Application" java.util.ConcurrentModificationException
我使用 Iterator 从 ArrayList 中删除对象,但现在我不知道如何在这种情况下使用它.
I used Iterator to remove objects from ArrayList but now I dont have an idea how to use it in this case.
推荐答案
这是因为某个线程实际上正在 for each 循环中查看此列表,也许您正试图在 for-each 的主体中删除此列表的元素?你不能在 for-each 中删除元素,但你可以在迭代器循环中:
It is because some thread is actually viewing this list in a for each loop, maybe you are trying to remove elements of this list in the body of for-each? You can't remove elements in for-each, but you can in iterator loops:
您可以使用迭代器代替 for each 来删除和查看列表中的元素,如下所示:
You can use iterator instead of for each to remove and view the elements of the list like this:
public static ArrayList<Meteorit> meteorits = new ArrayList<Meteorit>();
Iterator<Meteorit> itr = meteorits.iterator();
while (itr.hasNext()) {
if (itr.next()==this) {
itr.remove();
}
}
这篇关于Java,从 ArrayList 中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!