0

I need to delete elements recursively from a list, but even with an iterator applied to a copy of the subject, I get concurrent modification error.

List<Referee> referees=videogame.getGamers();
Iterator<Referee> iter= referees.iterator();

while(iter.hasNext()){
    Referee ref= iter.next();
    if(ref.getTheGameIsOver())
    videogame.removeReferee(ref);
}
Danielson
  • 2,605
  • 2
  • 28
  • 51
Vale
  • 1,104
  • 1
  • 10
  • 29
  • What does `removeReferee` do? Does it remove from the same `List` that `getGamers` returns and is iterated on by `iter`? – Sotirios Delimanolis Jun 26 '15 at 17:28
  • possible duplicate of [Calling remove in foreach loop in Java](http://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java) – Danielson Jun 26 '15 at 17:31
  • Or when using Java 8: `videogame.getGamers().removeIf(Referee::getTheGameIsOver);`… – Holger Jun 26 '15 at 17:41

2 Answers2

2

You are modifying the underlying collection while the Iterator is iterating over it. That is what is causing the ConcurrentModificationException.

Instead, call remove() on the Iterator itself. It removes the most recently iterated item with causing this exception. Replace

videogame.removeReferee(ref);

with

iter.remove();
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

The right way of using it will be as follows and it makes sense because the iterator object knows where it is in the list as the list is being navigated.

List<Referee> referees=videogame.getGamers();
Iterator<Referee> iter= referees.iterator();

while(iter.hasNext()){
    Referee ref= iter.next();
    if(ref.getTheGameIsOver())
    iter.remove()
}

Please refer http://durgaprasadtechie.blogspot.com/2011/07/concurrentmodificationexception-fail.html

KDP
  • 1,481
  • 7
  • 13