Search code examples
javacollectionsiteratorconcurrentmodification

Collection - Iterator.remove() vs Collection.remove()


As per Sun ,

"Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."

I have two questions :

  1. What makes this operation "Iterator.remove()" stable than the others ?
  2. Why did they provide a "Collection.remove()" method if it will not be useful in most of the use-cases?

Solution

  • If you're iterating over a collection and use:

    Collection.remove() 
    

    you can get runtime errors (specifically ConcurrentModifcationException) because you're changing the state of the object used previously to construct the explicit series of calls necessary to complete the loop.

    If you use:

    Iterator.remove()
    

    you tell the runtime that you would like to change the underlying collection AND re-evaluate the explicit series of calls necessary to complete the loop.