One of the most commonly used data structure used in programming is genericly called a collection. A collection is a group of objects in same type or sometimes casted to a base type like an_Object_ instance. Arrays, lists, vectors, maps whatever you can think about falls into this category.

This being said, a structure to iterate over these elements of group haves utmost importance. This is where the iterator comes in. Basicly it is an object that saves you a lot of time by preventing you to create a loop everytime you want to proccess the elements of group.

Intent Purpose is to let you reach to the objects of an aggregate object without exposing it’s underlying representation.

Lets create a generic iterator.

    public interface Iterator<T> {
    	public T next();
    	public boolean hasNext();

Now we need a class that will implement this and another class to nest them all.

    public class Farm {
    	Animal[] farmAnimals;
    	public Iterator<animal> createIterator(){
    		return new FarmIterator();
    	private class FarmIterator implements Iterator<animal>{
    		private int position=-1;
    		public Animal next() {
    			if (this.hasNext())
    				return farmAnimals[position++];
    				return null;
    		public boolean hasNext() {
    			if (position < farmAnimals.length)
    				return true;
    				return false;

As you can see the iteration mechanism is nested inside the our main class which is in this example. By doing this we are concealing our interation mechanism while providing a fully fledged interation mechanism to your liking.

This is considered as an internal interator where the iterator controls everything. There is another type of iterator where the collection elements controls the iteration which as you may have guess called external iterator.