Course contentsShow
← Java
Lesson 1272 of 2,87029. Iterators and IterableFree lesson

What Is an Iterator and Why Use It?

Learn the purpose of iterators: traversing collections without exposing their internal structure.

What Is an Iterator and Why Use It?

You'll learn what an iterator is and why Java provides this uniform way to traverse collections.

The Core Idea

An iterator is an object that lets you walk through a collection one element at a time, without needing to know how the collection stores its data internally. Think of it like a bookmark that moves through a book—you don't need to understand how the pages are bound or printed to read them in order.

Why We Need Iterators

Imagine you've been working with ArrayList, HashSet, LinkedList, and PriorityQueue. Each collection stores data differently:

  • ArrayList uses an internal array with indices
  • HashSet uses a hash table with buckets
  • LinkedList uses nodes with references
  • PriorityQueue uses a heap structure

Without iterators, you'd need to learn each collection's internal structure to traverse it. For an ArrayList, you might use indices; for a LinkedList, you'd need to follow node references. That's messy and exposes implementation details you shouldn't need to care about.

The Iterator Solution

An iterator provides a uniform interface for traversal. Every collection that can be traversed offers an iterator with the same basic operations:

  • Check if there are more elements
  • Get the next element
  • Optionally remove the current element

This means you can write code that processes "any collection" without knowing which specific type you're dealing with. The collection handles the traversal logic internally, and you just use the iterator's simple interface.

Key Takeaway: An iterator provides a standard way to traverse collections sequentially without exposing their internal structure, making your code more flexible and maintainable.