Here is a Java Program to Demonstrate the Simple Array Iterator.
Output of Above Java Program
apple
orange
apricot
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator that works over an array of Objects
* Use it: Iterator iter = new ArrayIterator( myArray );
*
*/
class SimpleArrayIterator implements Iterator{
/**
* True if we are debugging, includes main
* test driver code.
*/
static final boolean debugging = true;
/**
* Reference to the original array we will
* iterate over. Not a copy of the array.
*/
Object[] array;
/**
* How far down the array we have iterated so far.
*/
int pos;
/**
* public constructor
*
* @param a The array we are to iterate over. It must
* be an array of Objects of some sort not
* int[] etc.
*/
public SimpleArrayIterator( Object[] a ){
array = a;
pos = 0;
}
/**
* Is there yet another element in the array
* to go?
*
* @return true if there are more elements
*/
public boolean hasNext(){
return( pos < array.length );
}
/**
* Get the next element of the array.
*
* @return Next element of a the array. You must cast
* it back to its proper type from Object.
* @exception NoSuchElementException
*/
public Object next() throws NoSuchElementException{
if ( pos >= array.length )
throw new NoSuchElementException();
return array[pos++];
}
/**
* Remove the current object from the array.
* Not implemented.
*
* @exception UnsupportedOperationException
* @exception IllegalStateException
*/
public void remove() throws UnsupportedOperationException , IllegalStateException {
throw new UnsupportedOperationException();
}
public static void main ( String[] args ) {
if ( debugging ) {
String[] fruits = new String [] { "apple" , "orange" , "apricot"};
for ( Iterator iter = new SimpleArrayIterator( fruits ); iter.hasNext(); ) {
String key = (String) iter.next();
System.out.println( key );
}
}
}
}
Output of Above Java Program
apple
orange
apricot