Design Patterns in Java - Iterator Pattern
Last Updated :
08 Nov, 2023
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.
- Behavioral Design Pattern
- Creational Design Pattern
- Structural Design Pattern
|
Iterator Pattern | Factory Pattern | Adapter Pattern |
Interpreter Pattern | Abstract Factory Pattern | Bridge Pattern |
Mediator Pattern | Singleton Pattern | Composite Pattern |
Memento Pattern | Prototype Pattern | Decorator Pattern |
Observer Pattern | Builder Pattern | Facade Pattern |
State Pattern | Object Pool | Flyweight 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.
Example:
Java
// 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;
index++;
}
// Method 2
// Implementing the iterator method and
// adding your own implementation
@Override
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
@Override
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
@Override
public String next() {
return cars[currentIndex++];
}
// Method 5
@Override
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
cars.addCar("Dodge");
cars.addCar("Ferrari");
cars.addCar("Sedan");
// 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()) {
System.out.println(carIterator.next());
}
}
}
Conclusion:
- 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.
Further Read: Java Design Patterns Tutorial
Similar Reads
Java Design Patterns Tutorial Design patterns in Java refer to structured approaches involving objects and classes that aim to solve recurring design issues within specific contexts. These patterns offer reusable, general solutions to common problems encountered in software development, representing established best practices. B
8 min read
Creational Software Design Patterns in Java
Factory Method Design Pattern in Java It is a creational design pattern that talks about the creation of an object. The factory design pattern says to define an interface ( A java interface or an abstract class) for creating the object and let the subclasses decide which class to instantiate. Table of ContentWhat is the Factory Method D
6 min read
Builder Method Design Pattern in Java Method Chaining: In java, Method Chaining is used to invoke multiple methods on the same object which occurs as a single statement. Method-chaining is implemented by a series of methods that return the this reference for a class instance.Implementation: As return values of methods in a chain is this
5 min read
Builder, Fluent Builder, and Faceted Builder Method Design Pattern in Java Builder Pattern is defined as a creational design pattern that is used to construct a complex object step by step. It separates the construction of an object from its representation, allowing us to create different variations of an object with the same construction code. This pattern is particularly
8 min read
Singleton Design Pattern in Java Singleton Design Pattern is a creational design pattern that ensures a class has only one instance and provides a global point of access to it. This pattern is particularly useful when exactly one object is needed to coordinate actions across the system. Important Topics for Singleton Method in Java
5 min read
Structural Software Design Patterns in Java
Composite Design Pattern in Java The Composite Design Pattern is a structural design pattern that lets you compose objects into tree-like structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. In other words, whether dealing with a single object or a grou
8 min read
Decorator Method Design Pattern in Java A structural design pattern called the Decorator Design Pattern enables the dynamic addition of functionality to specific objects without changing the behavior of other objects in the same class. To wrap concrete components, a collection of decorator classes must be created. Decorator Method Design
10 min read
Design Patterns in Java - Iterator Pattern 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. U
5 min read