Iterator Design Pattern in Java
Iterator gives a standard way to go through the items of a collection one by one, without showing how the collection is built inside.
Real life example
Turning the pages of a book. You do not care how the book is bound.
When to use
You want to loop over a collection using a simple for-each loop.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
import java.util.*;
public class Main {
public static void main(String[] args) {
for (String name : new NameList()) {
System.out.println(name); // Ram, Sita, Amit
}
}
}
class NameList implements Iterable<String> {
private String[] names = {"Ram", "Sita", "Amit"};
public Iterator<String> iterator() {
return new Iterator<String>() {
private int i = 0;
public boolean hasNext() { return i < names.length; }
public String next() { return names[i++]; }
};
}
}Output
Ram
Sita
Amit