728x90 AdSpace

Saturday, 29 July 2017

Design Patterns - Iterator Pattern

Iterator Pattern


The Iterator design pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Where to use

Use to access the elements of an aggregate object sequentially. Java's collections like ArrayList and HashMap have implemented the iterator pattern.


•The same iterator can be used for different aggregates.
•Allows you to traverse the aggregate in different ways depending on your needs.
•It encapsulates the internal structure of how the iteration occurs.
•Don't need to bloat the your class with operations for different traversals.


Not thread safe unless its a robust iterator that allows insertions and deletions. This can be be solved by letting the Iterator use a Memento to capture the state of an iteration.

Iterator Pattern Class Diagram

Iterator Pattern Example

This example shows how you can write your own iterator.

import java.util.*;
public class BitSetIterator implements Iterator {
private final BitSet bitset;
private int index;
public BitSetIterator(BitSet bitset) {
this.bitset = bitset;
public boolean hasNext() {
return index < bitset.length();
public Boolean next() {
if (index >= bitset.length()) {
throw new NoSuchElementException();
boolean b = bitset.get(index++);
return new Boolean(b);
public void remove() {
throw new UnsupportedOperationException();

public class TestClientBitSet {
public static void main(String[] args) {
// create BitSet and set some bits
BitSet bitset = new BitSet();
BitSetIterator iter = new BitSetIterator(bitset);
while (iter.hasNext()) {
Boolean b = iter.next();
String tf = (b.booleanValue() ? "T" : "F");
When TestClientBitSet is executed the result is:

Usage example

This example shows how the Iterator of the ArrayList is used.

import java.util.*;
public class TestClientIterator {
public static void main(String[] args) {
ArrayList<Object> al = new ArrayList<Object>();
al.add(new Integer(42));
al.add(new String("test"));
al.add(new Double("-12.34"));
for(Iterator<Object> iter=al.iterator();
System.out.println( iter.next() );
// JEE5 syntax
for(Object o:al)
System.out.println( o );
When run the result is:

In the following class-diagram we illustrate the structure from the usage example of Iterator Pattern.

Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments


Post a Comment

Item Reviewed: Design Patterns - Iterator Pattern Rating: 5 Reviewed By: Annamalai Thangaraj