logo

Achieve Ultimate Excellence

Iterator Design Pattern - Access the Elements of a Collection in a Sequential Manner

Understanding the Iterator Design Pattern in Java

Understanding the Iterator Design Pattern in Java

Introduction

The Iterator design pattern is a behavioral pattern that provides a way to access the elements of a collection in a sequential manner without exposing the underlying representation of the collection. It decouples the traversal logic from the collection, making it easy to iterate over different types of collections using a common interface. In this blog post, we will delve into the details of the Iterator design pattern and illustrate its implementation in Java with a practical example.

Understanding the Iterator Design Pattern

The Iterator design pattern consists of two main components:

  1. Iterator: It defines the common interface for iterating over elements in the collection.

  2. Aggregate: It represents the collection of objects and provides a method to create an Iterator.

By using this pattern, clients can access the elements of the collection using the Iterator without worrying about the internal structure or implementation of the collection.

Implementation in Java

Step 1: Creating the Iterator Interface

// Iterator interface
public interface MyIterator {
    boolean hasNext();
    int next();
}

Step 2: Implementing the Aggregate (Collection)

import java.util.Arrays;

// Custom collection class
public class MyList {
    private int[] elements;
    
    public MyList(int[] elements) {
        this.elements = elements;
    }
    
    public MyIterator createIterator() {
        return new MyListIterator();
    }
    
    // Inner class for the iterator
    private class MyListIterator implements MyIterator {
        private int currentIndex;
        
        public MyListIterator() {
            this.currentIndex = 0;
        }
        
        @Override
        public boolean hasNext() {
            return currentIndex < elements.length;
        }
        
        @Override
        public int next() {
            return elements[currentIndex++];
        }
    }
}

Step 3: Utilizing the Iterator to Traverse the Collection

public class Main {
    public static void main(String[] args) {
        int[] data = {1, 2, 3, 4, 5};
        MyList myList = new MyList(data);
        
        // Create the Iterator
        MyIterator iterator = myList.createIterator();
        
        // Iterate over the elements using the Iterator
        System.out.println("Elements in MyList:");
        while (iterator.hasNext()) {
            int element = iterator.next();
            System.out.print(element + " ");
        }
    }
}

Explanation

  1. We create an interface called MyIterator, which defines the methods hasNext() to check if there are more elements to iterate, and next() to retrieve the next element.

  2. Next, we implement the custom collection class MyList with an array of integers as its internal representation. It has a method createIterator() that returns an instance of the inner class MyListIterator.

  3. The inner class MyListIterator implements the MyIterator interface. It keeps track of the current index and provides implementations for hasNext() and next() methods to traverse through the elements of the MyList.

  4. In the Main class, we demonstrate how to use the MyList collection and its associated MyIterator. We create a new MyList object with some sample data and then create an iterator using the createIterator() method.

  5. Finally, we use the iterator to iterate over the elements of the MyList, printing each element on the console.

Conclusion

The Iterator design pattern provides a clean and flexible way to traverse the elements of a collection without exposing its internal structure. By following the Iterator pattern, we ensure that the client code remains decoupled from the collection implementation. In this blog post, we demonstrated the implementation of the Iterator pattern in Java using a custom collection "MyList." Understanding and using the Iterator design pattern can greatly enhance the maintainability and extensibility of your code when dealing with collections and iterations.

avatar
Article By,
Create by
Browse Articles by Related Categories
Browse Articles by Related Tags
Share Article on:

Related posts

Related posts