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 right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.
Just remove the item by using it.remove()
while iterating.
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?
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
.
Remove the call to p.eggMoves.remove(selectedIndices[i]);
and it should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With