java ArrayList在迭代时删除对象
我正在arraylist上运行迭代器,并试图在条件为true时删除一个项 我有以下代码:java ArrayList在迭代时删除对象,java,arraylist,iterator,Java,Arraylist,Iterator,我正在arraylist上运行迭代器,并试图在条件为true时删除一个项 我有以下代码: 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
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]);
}
}
现在这段代码工作正常,该项从p对象和jlist中都被删除,但它在it.next()行抛出了一个“ConcurrentModificationException”异常
如何解决这个问题?不需要同时调用
和和p.egggmoves.remove(selecteddinces[i])代码>。调用it.remove()
将从p.eggMoves
中删除当前项目
删除对p.eggMoves.Remove的调用(selecteddinces[i])代码>应该可以正常工作。只需在迭代时使用it.remove()
删除该项即可
下面的行是导致问题的原因
p.eggMoves.remove(selectedIndices[i]);
通过一次又一次地删除同一项(即索引i处的项),您想做什么?此类迭代器和listIterator方法返回的迭代器很快就会失败:如果在迭代器创建后的任何时间,以任何方式修改列表的结构,除了通过迭代器自己的remove或add方法,迭代器将抛出ConcurrentModificationException。因此,在面对并发修改时,迭代器会快速、干净地失败,而不是在将来的不确定时间冒着任意、不确定行为的风险。
引自JavaDoc