Iterator Pattern in Java

by | Oct 20, 2020 | Java

Introduction

Normally every object-oriented programming language or otherwise has several data structures or collections of data that are used to hold together large chunks of valuable information but in independent identities. In order to retrieve information from such collections, a tool is required that will access all the information. The role of an iterator in such cases becomes important. Different collections have different rules for iterating through them. The Iterator Pattern is a simple yet useful design pattern that lets you iterate over a set of objects in a generic way irrespective of the collection type. This behavioral pattern also makes sure abstraction is put to practice by hiding the underlying representation.

Definition

As stated in the Gang of Four book, the Iterator Pattern is defined to ‘provide a way to access the elements of an aggregate object without exposing its underlying representation.’

Features of the Iterator Pattern

  • The pattern provides a generic way of traversing through object collections (not a particular type of list or collection).
  • The iterator produced from the pattern will have the capacity to iterate over a collection multiple times simultaneously from start to end or vice versa.
  • The information thus received after iteration should in no way reveal the internal structure of either the single entities or the collection as a whole.

Example and Code

The following example is a sample and generic way of understanding the use of an iterator. You might have seen this type of traversal before as it is a very common example.

.
.
List <String> collection = new ArrayList<String>();        //This will create a collection of strings
Iterator loop = collection.iterator();                  //Creation of an iterator object fo traversal               
while(loop.hasNext()){      //Checks if there is an element after the present one in the collection
String flag = loop.next();               
}
.
.

When to use the Iterator Pattern

This pattern should be used when an application requires a traversal of a long collection of objects with the objective of retrieving data either by searching, sorting, or any other traversal method.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.