java ArrayList在迭代时删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23818228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:23:40  来源:igfitidea点击:

java ArrayList remove object while iterating

javaarraylistiterator

提问by Ceri Turner

I'm running an iterator over an arraylist and am trying to remove an item when a condition is true.

我正在一个数组列表上运行一个迭代器,并试图在条件为真时删除一个项目。

I have the following code:

我有以下代码:

String item = (String) model.getElementAt(selectedIndices[i]);
Iterator it = p.eggMoves.iterator();
while(it.hasNext())
{
    String text = (String) it.next();
    if ( text.equals(item) )
    {
        it.remove();
        p.eggMoves.remove(selectedIndices[i]);
        model.removeElementAt(selectedIndices[i]);
    }
}

Now this code works fine, the item is removed from both the p object and the jlist, but it throws an "ConcurrentModificationException" exception at the it.next() line.

现在这段代码工作正常,项目从 p 对象和 jlist 中删除,但它在 it.next() 行抛出“ConcurrentModificationException”异常。

How do I solve this?

我该如何解决这个问题?

采纳答案by Braj

Just remove the item by using it.remove()while iterating.

只需it.remove()在迭代时使用即可删除项目。

Below line is causing the issue

下面的行导致了这个问题

p.eggMoves.remove(selectedIndices[i]);


What you want to do by removing same item (that is at index i) again and again?

您想通过一次又一次地删除相同的项目(即索引 i)来做什么?

回答by rgettman

There is no need to call both it.remove();and p.eggMoves.remove(selectedIndices[i]);. The call to it.remove();will remove the current item from p.eggMoves.

没有必要同时调用it.remove();p.eggMoves.remove(selectedIndices[i]);。调用it.remove();将从 中删除当前项目p.eggMoves

Remove the call to p.eggMoves.remove(selectedIndices[i]);and it should work fine.

删除对的调用p.eggMoves.remove(selectedIndices[i]);,它应该可以正常工作。