CodesJava

Easy learning with example program codes

java iterator design pattern


An iterator is an object that enables a programmer to traverse through a group of objects like lists, set etc.

Java iterator design pattern comes under behavioural design patterns. According to GoF, iterator design pattern states that Provides a way to access the elements of an aggregate object without exposing its underlying representation.

Java iterator design pattern is commonly used in collection framework to traverse through collection objects.

Example

Iterator.java

package com.codesjava;
 
public interface Iterator {
	public boolean hasNext();
	public Object next();
}

Container.java

package com.codesjava;
 
public interface Container {
	public Iterator getIterator();
}

NamesCollection.java

package com.codesjava;
 
public class NamesCollection implements Container{
   public String names[] = {"Jai" , "Sahil" ,"Sachin" , "Vijay", "Binod"};
 
   @Override
   public Iterator getIterator() {
      return new NameIterator();
   }
 
   private 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;
      }		
   }
}

InterpreterPatternTest.java

package com.codesjava;
 
public class InterpreterPatternTest {
	public static void main(String args[]){
		  NamesCollection namesCollection = new NamesCollection();
		  System.out.println("Names: ");
	      for(Iterator iter = namesCollection.getIterator(); iter.hasNext();){
	         String name = (String)iter.next();
	         System.out.println(name);
	      } 	
	}
}

Output

Names: 
Jai
Sahil
Sachin
Vijay
Binod
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki