tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Design Patterns > Java Design Patterns > Iterator

Iterator 

Iterator pattern comes under Behavioral design pattern. It provides a means through iterate through a collection of objects without knowing its internal representation.

Behaviour & Advantages

  • Standardizes aggregate object traversal irrespective of its representation.
  • Decouples the iteration logic from its container.

In this example we show a simple collection which internally stores a list of strings. Java provides two useful interfaces java.lang.Iterable which tells that this collection would return an Iterator and interface java.util.Iterator which defines abstract interface for actual traversal.

java.lang.Iterable
public abstract interface Iterable<T>
{
  public abstract Iterator<T> iterator();
}
java.util.Iterator
public abstract interface Iterator<E>
{
  public abstract boolean hasNext();

  public abstract E next();

  public abstract void remove();
}
We can observe that though SimpleCollection accepts a string array, internally its represented as list of strings. Irrespective of its internal representation we can traverse the data using Iterator.

File Name  :  
com/bethecoder/tutorials/dp/iterator/SimpleCollection.java 
   
package com.bethecoder.tutorials.dp.iterator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class SimpleCollection implements Iterable<String> {

  private List<String> items = new ArrayList<String>()

  public SimpleCollection(String [] strList) {
    this.items.addAll(Arrays.asList(strList));
  }

  @Override
  public Iterator<String> iterator() {
    
    //Underlying Iterator implementation
    //Anonymous to the user.
    return new Iterator<String>() {

      int index = 0;
      
      @Override
      public boolean hasNext() {
        return index < items.size();
      }

      @Override
      public String next() {
        return items.get(index++);
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException(
            "Remove operation is not supported by current implementation of iterator.");
      }
      
    };
  }
}
   

Iterator usage is shown below,

File Name  :  
com/bethecoder/tutorials/dp/iterator/Test.java 
   
package com.bethecoder.tutorials.dp.iterator;

import java.util.Iterator;

public class Test {

  /**
   @param args
   */
  public static void main(String[] args) {

    String [] list = "ONE""TWO""THREE""FOUR""FIVE""SIX" };
    SimpleCollection collection = new SimpleCollection(list);
    
    //Here we get anonymous implementation of iterator
    //and we don't know how the initial string list is
    //stored in SimpleCollection
    Iterator<String> it = collection.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
    }
    
    System.out.println("------------------");
    
    //Implementing 'Iterable' interface makes an object to be
    //target of 'for each' loop to get associated Iterator.
    for (String str : collection) {
      System.out.println(str);
    }
  }

}
   

It gives the following output,
ONE
TWO
THREE
FOUR
FIVE
SIX
------------------
ONE
TWO
THREE
FOUR
FIVE
SIX



 
  


  
bl  br