问题:
We all know you can't do the following because of ConcurrentModificationException
: 我们都知道,由于ConcurrentModificationException
您无法执行以下操作:
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
But this apparently works sometimes, but not always. 但这显然有时有效,但并非总是如此。 Here's some specific code: 这是一些特定的代码:
public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
This, of course, results in: 当然,这导致:
Exception in thread "main" java.util.ConcurrentModificationException
Even though multiple threads aren't doing it. 即使没有多个线程。 Anyway. 无论如何。
What's the best solution to this problem? 解决此问题的最佳方法是什么? How can I remove an item from the collection in a loop without throwing this exception? 如何在不引发此异常的情况下循环从集合中删除项目?
I'm also using an arbitrary Collection
here, not necessarily an ArrayList
, so you can't rely on get
. 我还在这里使用任意Collection
,不一定是ArrayList
,所以您不能依赖get
。
解决方案:
参考一: https://stackoom.com/question/wFa/遍历Collection-避免在循环中删除对象时避免ConcurrentModificationException参考二: https://oldbug.net/q/wFa/Iterating-through-a-Collection-avoiding-ConcurrentModificationException-when-removing-objects-in-a-loop
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/4310762