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?

ashatte
  • 5,442
  • 8
  • 39
  • 50
Ceri Turner
  • 830
  • 2
  • 12
  • 36
  • `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 – Haifeng Zhang May 22 '14 at 22:46

2 Answers2

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?

Braj
  • 46,415
  • 5
  • 60
  • 76
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.

rgettman
  • 176,041
  • 30
  • 275
  • 357