How to Implement Iterator Pattern in Java


Here this example will help us learn how to implement Iterator Pattern in Java.

Source Code

package com.beginner.examples;

//iterator
interface Iterator {
	 public boolean hasNext();
	 public Object next();
}
// detail iterator
class DetailIterator implements Iterator {
    private List list = null;
    private int index;

    public DetailIterator(List list) {
        super();
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        if (index >= list.getSize()) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Object next() {
        Object object = list.get(index);
        index++;
        return object;
    }

}


//list
interface List {

  public void add(Object obj);  
  public Object get(int index);
  public Iterator iterator();  
  public int getSize();
}

// container 
class Container implements List{

    private Object[] list;
    private int size = 0;
    private int index = 0;
    public Container(){
        index = 0;
        size = 0;
        list = new Object[50];
    }
    @Override
    public void add(Object obj) {
        list[index++]=obj;
        size++;
    }

    @Override
    public Iterator iterator() {
        
        return new DetailIterator(this);
    }
    @Override
    public Object get(int index) {
        
        return list[index];
    }
    @Override
    public int getSize() {
        
        return size;
    }

}

public class IteratorExample {

    public static void main(String[] args) {

        List list = new Container();
        list.add("1");
        list.add("2");
        list.add("3");
        Iterator i = list.iterator();
        while(i.hasNext()){
            System.out.println(i.next());
        }
    }

}

Output:

1
2
3
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments