Overview
The Iterator Design Pattern provides a way to access the elements of a collection sequentially without exposing its underlying representation. It is commonly used to traverse collections such as lists, sets, or maps.
Key Characteristics
- Decouples iteration logic from the collection's implementation.
- Supports multiple traversal algorithms over the same collection.
- Provides a uniform interface for iterating over different types of collections.
Implementation
The following is an example of an Iterator implementation in Java:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
// Collection
class BookCollection implements Iterable {
private List books = new ArrayList<>();
public void addBook(String book) {
books.add(book);
}
public void removeBook(String book) {
books.remove(book);
}
@Override
public Iterator iterator() {
return books.iterator();
}
}
// Demo
public class IteratorDemo {
public static void main(String[] args) {
BookCollection collection = new BookCollection();
collection.addBook("Book 1");
collection.addBook("Book 2");
collection.addBook("Book 3");
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Enhanced for loop (for-each) with Iterable
for (String book : collection) {
System.out.println("[Enhanced] " + book);
}
}
}
When to Use
- When you need to traverse elements in a collection without exposing its internal details.
- When multiple types of collections need to provide a common traversal mechanism.
Advantages
- Decouples the collection from traversal logic.
- Supports multiple traversal algorithms over the same collection.
Disadvantages
- Can add overhead if the collection's size or complexity is very small.