Top 3 Iterators Interview Questions
Browse 3 real-world technical and behavioral interview questions about Iterators. Review scenarios, edge cases, and architectural best practices.
How do you remove elements from a collection while iterating it, and what makes an iterator fail-fast?
Structural modification through the collection during a for-each invalidates the iterator, which detects it by comparing a modification counter and throws ConcurrentModificationException. Remove through the iterator, or use removeIf, or pick a collection whose iterator is weakly consistent instead.
How do generators reduce memory use, and when are they the wrong choice?
A generator produces items on demand and keeps only the current item plus its suspended frame, so memory stays flat as the input grows; it is the wrong tool when you need a length, indexing, or more than one pass, and when per-item resume overhead outweighs the space saved.
You build a LINQ query, then change the list it came from, then enumerate it. What do you get?
The results reflect the list and the captured variables as they are at enumeration time, not at query construction, because a LINQ-to-objects query is an iterator holding references rather than a snapshot. Enumerating it twice runs the whole chain twice. It also connects deferred execution to the point an interviewer is testing.