Skip to content
Related Articles
Open in App
Not now

Related Articles

Design Patterns in Java – Iterator Pattern

Improve Article
Save Article
  • Last Updated : 28 Dec, 2022
Improve Article
Save Article

A design pattern is proved solution for solving the specific problem/task. We need to keep in mind that design patterns are programming language independent for solving the common object-oriented design problems. In Other Words, a design pattern represents an idea, not a particular implementation. Using design patterns you can make your code more flexible, reusable, and maintainable.

Types of design patterns: There are 3 types of Design Patterns in java that are depicted more clearly in a tabular format below.

  1. Behavioral Design Pattern
  2. Creational Design Pattern
  3. Structural Design Pattern
Iterator PatternFactory PatternAdapter Pattern
Interpreter PatternAbstract Factory PatternBridge Pattern
Mediator PatternSingleton PatternComposite Pattern
Memento PatternPrototype PatternDecorator Pattern
Observer PatternBuilder PatternFacade Pattern
State PatternObject PoolFlyweight Pattern
Strategy Pattern Proxy Pattern
Template Pattern  
Visitor Pattern  

Behavioural – Iterator Pattern

Here we will be discussing Iterator Pattern with an example.

  • The iterator pattern is a great pattern for providing navigation without exposing the structure of an object.
  • Traverse a container. In Java and most current programming languages, there’s the notion of a collection. List, Maps, Sets are all examples of a collection that we would want to traverse. Historically we use a loop of some sort and index into your collection to traverse it.
  • Doesn’t expose the underlying structure of the object we want to navigate. Navigating various structures may have different algorithms or approaches to cycle through the data.
  • Decouples the data from the algorithm used to traverse it

Design: Iterator Pattern

  • It is an interface-based design pattern. Whichever object you want to iterate over will provide a method to return an instance of an iterator from it.
  • Follows a factory-based method pattern in the way you get an instance of the iterator.
  • Each iterator is developed in such a way that it is independent of another.
  • Iterators also Fail Fast. Fail Fast means that iterators can’t modify the underlying object without an error being thrown.

  • The Collection interface is extended by the List Interface.
  • List Interface contains a factory method iterator(). This iterator factory method returns an instance of the Iterator Interface.
  • In the case of the list and its implementations, the underlying instances are ListIterator.
  • The ListIterator is an implementation of the Iterator interface that understands how to iterate over the various list objects in the Collection API. It declares the interface for objects in the composition.

There are some pitfalls of iterator which are as follows:

  • You don’t have access to an index of any sort. If you want to get an element of a certain position, there is no way to do that without just iterating though. In the case of sets and maps, there isn’t a method to grab an element at a certain index position
  • UniDirectional: It iterates objects in forwarding direction only.
  • Although iterator is the most efficient way to looping through objects of any sort. But in some cases, it may be slower than using an index and looping through it.



// Java Program to Implement Behavioral>Iterator Pattern
// importing required package to
// implement Behavioral>Iterator Pattern
package com.demo.application;
// Importing required libraries
// Here Iterator Interface to
// use it to iterate over the elements
import java.util.Iterator;
// Class 1
// Car Class Implementing Iterable Interface so
// that we can implement the iterator method and
// add our own implementation
public class Car implements Iterable<String> {
  private String[] cars;
  private int index;
  // Default Constructor
  public Car() {
    cars = new String[10];
    index = 0;
  // Method 1
  // Adding method to add Cars
  public void addCar(String car) {
    if (index == cars.length) {
      String[] largerCars = new String[cars.length + 5];
      System.arraycopy(cars, 0, largerCars, 0, cars.length);
      cars = largerCars;
      largerCars = null;
    cars[index] = car;
  // Method 2
  // Implementing the iterator method and
  // adding your own implementation
  public Iterator<String> iterator() {
    Iterator<String> it = new Iterator<String>() {
      private int currentIndex = 0;
      // Method 3
      // Finding whether during iteration if
      // there is next element or not
      public boolean hasNext() {
        return currentIndex < cars.length && cars[currentIndex] != null;
      // Method 4
      // Going to grab each car element by one by one
      // according to the index
      public String next() {
        return cars[currentIndex++];
      // Method 5
      public void remove() {
        throw new UnsupportedOperationException();
    return it;
  // Method 6
  // Main driver method
  public static void main(String[] args) {
    // Instantiating Car object
    Car cars = new Car();
    // Adding cars to the Array
    // Creating an Iterator and pointing the cursor
    // to the index just before the first element in cars
    Iterator<String> carIterator = cars.iterator();
    // Checking whether the next element is available or not
    while (carIterator.hasNext()) {


  • An iterator is an efficient way to traverse an object.
  • Hides the algorithm from the client, so that simplicity for your client is contained within the algorithm that you have coated in the container you’re creating an iterator for
  • Helps us to simplify that client.
  • Helps us to take advantage of the for each syntax which definitely simplifies iterating over that object in a for each loop.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!