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.w3schools; public interface Iterator { public boolean hasNext(); public Object next(); } |
Container.java
package com.w3schools; public interface Container { public Iterator getIterator(); } |
NamesCollection.java
package com.w3schools; 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.w3schools; 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 |