Why does an iterator's current position live on the iterator object itself, rather than on the collection being traversed?
If the current traversal position were stored as a field on the collection instead of on a separate iterator object, only one traversal could ever be in progress at a time — a second caller starting to iterate would either interfere with the first caller's position or be forced to wait. By keeping position as a field on a fresh iterator object returned each time traversal starts, any number of independent callers can iterate over the exact same collection simultaneously, each with its own private notion of where it currently is, without any of them stepping on each other. This is exactly why methods like createIterator() or Iterable's iterator() return a new object on every call rather than a single shared instance.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response