Java Design Patterns Tutorial - Java Design Pattern - Iterator Pattern








Iterator pattern accesses the elements of a collection object in sequential manner without knowing its underlying representation.

Iterator pattern is one of the behavioral patterns.

Example

interface Iterator {
   public boolean hasNext();
   public Object next();
}/*from w w w  . j a  v  a  2  s .  c  om*/
class LetterBag {
   public String names[] = {"R" , "J" ,"A" , "L"};
   public Iterator getIterator() {
      return new NameIterator();
   }
   class NameIterator implements Iterator {
      int index;
      @Override
      public boolean hasNext() {
         if(index < names.length){
            return true;
         }
         return false;
      }
      @Override
      public Object next() {
         if(this.hasNext()){
            return names[index++];
         }
         return null;
      }    
   }
}
public class Main {
   public static void main(String[] args) {
      LetterBag bag = new LetterBag();
      for(Iterator iter = bag.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      }   
   }
}

The code above generates the following result.