Thursday, August 18, 2011

Implement Array Iterator in JAVA

Iterator is very important part of programming, I don't think that any programmer has not ever used this Iterator. have you ever think what is the internal structure of the Iterator and how does it works? Generally it is used with collection to iterate over elements of the collection.

One of the question asked in Google interview to implement Iterator's methods "hasNext" and "next" for the array. the The Iterator must be generic to accept different kind of array. In fact, this question can be asked for different data structure like
Implement Iterator for binary tree, for linked list etc.
But after this implementation you would have fair idea of iterator and how to implement it

Here is the detail class code. The main method contains the code to test the class functionality.




package com.interview;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayIterator<T> implements Iterator<T> {
T[] a;
int counter = 0;

public ArrayIterator(T[] a) {
this.a = a;
}

@Override
public boolean hasNext() {
return counter < a.length;
}

@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T t = a[counter];
counter++;
return t;
}

@Override
public void remove() {

}

public static void main(String[] a) {
Integer [] array = new Integer[] { 1, null, 4, 3, 5 };
ArrayIterator<Integer> it = new ArrayIterator<Integer>(array);
while(it.hasNext()){
System.out.println(it.next());
}
}
}



I would love to have your comment on code and also your questions. Please privde your feedback on code.

1 comment:

  1. Nice article, you have indeed covered the iterators well. I have also blogged my experience as What is Iterator and ListIterator in Java , please let me know how do you find it.

    ReplyDelete