OOP Design Patterns — Iterator Pattern

Dinesha Karunathilake
2 min readApr 22, 2021

Suppose we have 2 types of collections (Array and a List) but we need to traverse both the collections in a client.

//array
for (int i = 0; i < taskList.length; i++)
Task task = taskList[i]);
//arraylist
for (int i = 0; i < taskList.size(); i++)
Task task = (Task)taskList.get(i);

But it might not be optimal to check for the type of collection, know its implementation and iterate over the collection. We know we should encapsulate what changes, the iteration caused by the different collections as of here.

The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation or the internal structure.

An ITERATOR takes the job of iterating over aggregate and encapsulates is in another object. It provides a common interface for traversing items of an aggregate allowing us to use polymorphism when writing code that makes use of the items of the aggregate.

JAVA has its inbuilt iterator for most of the collections and we can build our own otherwise.

public class App {


private static Iterator<Person> getPeople(final int count) {
return new Iterator<Person>() {

private int index = 0;
@Override
public boolean hasNext() {
return index < count;
}

@Override
public Person next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
index++;
return new Person((" "+ index));
}

@Override
public void remove() {

}


};

}
public static void main( String[] args ) {
Iterator iterator = getPeople(10);

while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

--

--