I want to use Iterator to remove an item. Like that:

List<Element> elements = obj.getElements(); Iterator<Element> it = elements.iterator(); while (it.hasNext()) { Element el = it.next(); if (el.getCounter() < minValue || el.getCounter() > maxValue) { elements.remove(queue); } } return queues; 

However, I get a ConcurrentModificationException on line 4 on the second pass of the loop. Tell me how to fix this error?

  • Use the remove method of the iterator - it.remove() will remove the desired item from the collection. But again, if during an iterator some object flew into the collection - say ConcurrentModificationException - And

1 answer 1

In this case, ConcurrentModificationException arises from the fact that you, iterating over the collection, change this very collection.

Remove items from the collection with an iterator using the remove() method, which removes the current item.