简体   繁体   中英

If Iterators returned by HashSet, ArrayList are fail-fast, how can we use iterator remove() to remove elements from Collection

As we all know that Iterator s returned by ArrayList , HashMap , HashSet etc. are fail-fast, but while using iterator's remove() doesn't throw ConcurrentModificationException . How?

fail-fast iterators throw ConcurrentModificationException if a collection is modified while iterating over it. But while removing elements from ArrayList or HashSet using iterator's remove() , doesn't throw any ConcurrentModificationException . Please explain elaborately.

Thanks

but while using iterator's remove() doesn't throw ConcurrentModificationException. How?

Because that behaviour is explicitly documented.

For ArrayList :

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 .

For HashSet :

if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException .

If instead you're asking how that's achieved , well, the source code (at least for OpenJDK) is freely available (and likely explorable directly from your IDE) :)

It is achieved as follows:

The collection contains a private int member called modificationCount (or something like that.) Each time you use one of the methods that modify the collection, this modificationCount is incremented. When you create an iterator on a collection, the iterator takes notice of the current value of modificationCount of the collection, and each time you invoke the iterator it makes sure that modificationCount has not changed, so as to ensure that the collection has not been modified while iterating. If the iterator finds that modificationCount has changed, it throws a ConcurrentModificationException .

When you delete via the iterator , the iterator refrains from incrementing the modificationCount of the collection. It is that simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM