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.
How do I solve this?
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.quotes from JavaDoc