5

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?

1
  • 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 Commented May 22, 2014 at 22:46

2 Answers 2

13

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?

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.