Iterator Pattern Explained: Real‑World Scenarios and Java Code
This article demystifies the Iterator design pattern by describing its purpose of separating collection storage from traversal, illustrating everyday analogies, presenting a complete Java implementation—including interfaces, concrete aggregate, custom iterator, and test code—and summarizing typical applications, advantages, and drawbacks.
What is the Iterator Pattern?
In plain terms, the Iterator pattern extracts collection‑traversal logic into an independent iterator that exposes only two operations to the client: retrieving the next element and checking whether another element exists. Users do not need to know whether the underlying collection is an array, a linked list, or a tree.
The core purpose is to decouple storage from traversal, providing a uniform traversal interface that works with many kinds of containers.
Real‑World Scenarios
Package pickup codes: whether a parcel is on a shelf or in a locker, it can be taken out sequentially.
Software: JDK’s built‑in Iterator traverses List/Set, and custom tree‑menu iterators traverse hierarchical structures.
Pagination data, database result sets, and heterogeneous data sources can all be wrapped for uniform iteration.
Java Code Implementation (Custom Goods Collection)
1. Unified Iterator Interface
public interface Iterator {
boolean hasNext();
Object next();
}2. Goods Entity
public class Goods {
private String name;
public Goods(String name){
this.name = name;
}
public String getName(){
return name;
}
}3. Aggregate Interface
public interface GoodsAggregate {
Iterator getIterator();
}4. Concrete Aggregate (GoodsList)
public class GoodsList implements GoodsAggregate{
private Goods[] goodsArr;
private int index = 0;
public GoodsList(int size){
goodsArr = new Goods[size];
}
// Add a product
public void add(Goods goods){
goodsArr[index++] = goods;
}
@Override
public Iterator getIterator() {
return new GoodsIterator(goodsArr);
}
}5. Custom Iterator (GoodsIterator)
public class GoodsIterator implements Iterator{
private Goods[] arr;
private int pos = 0;
public GoodsIterator(Goods[] arr){
this.arr = arr;
}
@Override
public boolean hasNext() {
return pos < arr.length && arr[pos] != null;
}
@Override
public Object next() {
return arr[pos++];
}
}6. Test Traversal
public class Test {
public static void main(String[] args) {
GoodsList list = new GoodsList(3);
list.add(new Goods("T恤"));
list.add(new Goods("裤子"));
list.add(new Goods("鞋子"));
Iterator it = list.getIterator();
while(it.hasNext()){
Goods g = (Goods) it.next();
System.out.println(g.getName());
}
}
}Common Business Scenarios for the Iterator Pattern
Need to traverse multiple collections with different underlying structures (arrays, linked lists, trees) using a single interface.
JDK collection framework: List, Set, Map all provide built‑in iterators.
Uniform traversal of database query result sets and paginated lists.
Recursive iteration tools for tree menus and multi‑level categories.
Unified looping over merged heterogeneous data sources.
Pros and Cons
Advantages: Decouples collection from traversal; adding a new container only requires a matching iterator.
Disadvantages: For simple collections the extra iterator class adds code overhead.
Conclusion and Next Topic
The 16th episode on the Iterator pattern is complete. The next update will cover the Mediator pattern, keeping the series on track.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
