Provide a way to access elements of a collection sequentially without exposing its representation. You want consistent traversal across differen
Iterator
Overview
Provide a way to access elements of a collection sequentially without exposing its representation.
When to use
- You want consistent traversal across different structures.
- You need multiple traversal strategies.
Java example
TypeScript example
Pros and cons
Pros:
- Hides internal structure.
- Enables multiple traversal algorithms.
Cons:
- Extra objects for simple collections.
Common pitfalls
- Exposing mutable internals through iterator.
- Ignoring concurrent modification semantics.