Java ArrayList removes object during iteration

I run an iterator over an arraylist and try to remove the element when the 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 element is deleted both from the p-object and from the jlist, but it throws a "ConcurrentModificationException" exception in the it.next () line.

How to solve this?

+4
source share
2 answers

Just remove the item using it.remove()during iteration.

Below line causes problem

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

What do you want to do by deleting the same element (i.e. in index i) again and again?

+11
source

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

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

+4

Source: https://habr.com/ru/post/1541692/


All Articles