Interview Q&A · Java · 6 questions in this topic

Iterators: Iterator, ListIterator, Fail-Fast and Fail-Safe — Java Interview Q&A

All Java topics

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

Example.javajava
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

Example.javajava
ListIterator<String> li = list.listIterator();
while (li.hasNext()) {
    String s = li.next();
    li.set(s.trim());
}

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits