Skip to content

Design Patterns

Iterator

Walking through all n items takes O(n) time — the time grows with n. Each single step takes O(1) time (a constant amount).

The idea, in plain English

An iterator works like a TV remote flipping through channels. You press 'next' and get the next channel. You never see how the channels are wired up behind the screen. In code, an iterator lets you step through a collection of items, one at a time, without knowing how it's stored inside.

How it works

  1. 1The collection hands you an iterator, instead of its raw internal data.
  2. 2The iterator tracks its own position. It offers a 'hasNext' check and a 'next' step.
  3. 3You loop: while there's a next item, you ask for it and use it. The collection's internal storage stays hidden.

When you'd use it

Use this when you want to walk through any collection — a list, a tree, or a custom data structure — the same simple way, without caring how it's stored inside.

Common beginner mistakes

  • Always check 'hasNext' before calling 'next'. Skipping this can run you off the end of the collection.
  • Don't share one iterator's position across code that expects to start over from the beginning.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Song A
Song B
Song C

Not sure this is the right topic? See the learning paths → or where this leads →