Java,从ArrayList中删除对象 [英] Java , Removing object from ArrayList

查看:103
本文介绍了Java,从ArrayList中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ClassA,它有一个静态的ArrayList of Objects

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.

推荐答案

这是因为某些线程实际上是在每个循环中查看此列表,也许您尝试删除此列表的元素在每个人的身体?你不能删除每个中的元素,但你可以在迭代器循环中:

It is because some thread is actually viewing this list in a for each loop, maybe you try 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:

你可以使用迭代器而不是每个来删除和查看列表的元素,如这个:

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中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆