Java , 从 ArrayList 中移除对象

Java , Removing object from ArrayList

我有一个 ClassA,它有一个对象的静态 ArrayList

public static ArrayList<Meteorit> meteorits = new ArrayList<Meteorit>();

现在我想像这样从此列表中删除一个对象

ClassA.meteorits.remove(this);

这是用 Meteorit 写的class。但是当我想使用 ArrayList 中的对象时它抛出异常。

Exception in thread "LWJGL Application" java.util.ConcurrentModificationException

我使用 Iterator 从 ArrayList 中删除对象,但现在我不知道如何在这种情况下使用它。

使用迭代器时;您需要使用迭代器从列表中删除项目:

iterator.remove();

Java 文档中说:

Removes from the underlying collection the last element returned by this iterator.

通过任何其他方式从列表中删除项目将导致您看到的 ConcurrentModificationException。

Iterator<Integer> itr = yourlist.iterator();

// remove all even numbers
while (itr.hasNext()) {
       itr.remove();
}

这一定对您有用,解决此问题的其他方法是使用 CopyOnWriteArrayList,希望它能有所帮助。

这是因为某些线程实际上正在 for each 循环中查看此列表,也许您正试图在 for-each 的主体中删除此列表的元素?您不能在 for-each 中删除元素,但可以在迭代器循环中删除:

您可以使用迭代器而不是 for each 来删除和查看列表的元素,如下所示:

public static ArrayList<Meteorit> meteorits = new ArrayList<Meteorit>();

Iterator<Meteorit> itr = meteorits.iterator();

while (itr.hasNext()) {
       if (itr.next()==this) {
          itr.remove();
       }
}

基本上,你需要使用迭代器来避免这种并发修改:

List<String> list = new ArrayList<>();
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        iterator.remove();
    }
}

更多详情,请查看此post:

Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop