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.
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