Creating Custom Iterators in Java

with the (over?)dependence on the standard Java Iterators, we sometimes overlook/forget the fact that we can , in fact, define custom iterators. This can be  quite simple to do, depending on the underlying data structure you define. The following is a simple example of how to define and use a custom list iterator.

1. Define the list node

package com.vgb.iterexample;



public class SampleNode {

	int i;
	SampleNode next;


	
	public SampleNode(int i, SampleNode next) {
		super();
		this.i = i;
		this.next = next;
	}

	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}

	public SampleNode getNext() {
		return next;
	}

	public void setNext(SampleNode next) {
		this.next = next;
	}
	
	public String toString() {
		return i+"";
	}
	
}

2. Define an iterator for this node

package com.vgb.iterexample;

import java.util.Iterator;

public class SampleNodeIterator implements Iterator{
	public SampleNode cur = null;
	
	
	
	public SampleNodeIterator(SampleNode cur) {
		super();
		this.cur = cur;
	}

	@Override
	public boolean hasNext() {
		if (cur == null)
			return false;
		
		return true;
	}

	@Override
	public Object next() {
		if (cur == null)
			return null;
		
		SampleNode tmp = cur;
		cur = cur.getNext();
		return tmp;
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub
		
	}

}

3. Define the list that uses these nodes

package com.vgb.iterexample;

import java.util.Iterator;

public class SampleList implements Iterable {
	SampleNode head = null;

	@Override
	public Iterator iterator() {
		return new SampleNodeIterator(head);
	}

	public SampleList() {
		head = new SampleNode(-1, null);
	}

	/*
	 * NOTE: shallow value - of - reference copy
	 */
	public void addNodetoList(SampleNode node) {
		if (head == null) {
			head = node;
			node.setNext(null);
		} else {
			node.setNext(head.getNext());
			head.setNext(node);
		}
	}
}

4. .. and finally, a simple test application

package com.vgb.iterexample;

import java.util.Iterator;

public class SampleApp {

	public static void main(String argv[]) {
		SampleList sList = new SampleList();
		
		for (int i = 0; i < 10;i++) {
			sList.addNodetoList(new SampleNode(i, null));
		}
		
		Iterator iter = sList.iterator();
		SampleNode sNode = null;
		while (iter.hasNext()) {
			sNode = (SampleNode) iter.next();
			System.out.println("retrived via iterator: " + sNode);
		}
		
	}
	
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s