Interview Q&A · Java · 6 questions in this topic
Iterators: Iterator, ListIterator, Fail-Fast and Fail-Safe — Java Interview Q&A
How to traverse collections with Iterator and ListIterator, and how fail-fast and fail-safe iterators behave under concurrent modification. Part of Collections Framework · 294 questions in the Java bank.
What is Iterator and what are its methods?
Answer
Iterator is the standard object for visiting each element of a collection one at a time without exposing its storage. You obtain one from collection.iterator, then loop with hasNext to test for another element, next to fetch it, and the optional remove to delete the last returned element. Always call hasNext before next, because calling next when no element remains throws NoSuchElementException. Modern for-each loops and streams use this protocol internally, but calling it directly still matters for removal during traversal.
Example
Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); if (s.isEmpty()) { it.remove(); } }
💡 Mention the guard rule: check hasNext before next to avoid NoSuchElementException.
In which order does an Iterator iterate?
Answer
An Iterator has no order of its own and simply follows the traversal order of the underlying collection. For lists the order is insertion or index order, so ArrayList and LinkedList iterate in the sequence you added. For HashSet and HashMap the order is undefined and may change with hashing and capacity. For TreeSet, TreeMap, and other sorted collections the order is the sorted or comparator-defined order.
What is ListIterator?
Answer
ListIterator is a bidirectional iterator available only for lists, obtained from list.listIterator or list.listIterator with a start index. Beyond hasNext and next, it adds hasPrevious and previous for reverse traversal, nextIndex and previousIndex for positions, plus add, set, and remove for in-place modification. Its cursor sits between elements rather than on one, so next returns the element ahead and previous returns the element behind. This design makes it ideal for stepping forward and backward or editing a list while walking it.
Example
ListIterator<String> li = list.listIterator(); while (li.hasNext()) { String s = li.next(); li.set(s.trim()); }
What is CopyOnWriteArrayList and when is it used?
Answer
CopyOnWriteArrayList is a thread-safe List in java.util.concurrent designed for read-heavy concurrent use. Every mutating operation copies the entire backing array, so readers traverse a stable snapshot without locking. Reads are therefore lock free and never throw ConcurrentModificationException, while iterators see the array as it was when they were created. Use it when reads vastly outnumber writes, such as listener lists, and avoid it when writes are frequent because each write pays a full copy.
What are fail-fast iterators?
Answer
Fail-fast iterators detect structural modification of their collection during iteration and fail quickly by throwing ConcurrentModificationException. The modification may come from another thread or from the same thread calling collection methods instead of the iterator remove method. Most java.util collections behave this way, including ArrayList, HashSet, HashMap, LinkedList, and TreeSet. The exception is a safety signal, not a synchronization tool, so concurrent code must use explicit locking or a concurrent collection instead.
What are fail-safe (weakly consistent) iterators?
Answer
Fail-safe is the informal name for iterators that tolerate concurrent modification instead of throwing ConcurrentModificationException. They usually traverse a snapshot or a live structure designed for concurrency, so they reflect some recent state without guaranteeing every concurrent update. CopyOnWriteArrayList iterators walk an immutable array snapshot, while ConcurrentHashMap iterators are weakly consistent over bins updated with CAS and fine-grained locks. Use them when readers must keep moving while writers update, accepting that they may miss very recent changes.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission