Definition: The Iterator pattern allows sequential access to the elements of an collection of objects without exposing the collection's underlying implementation.
Usage: Use this pattern to iterate over collections. This pattern is used extensively by the java.util Collection classes, though it can be used for any situation in which objects must be iterated over.
In some cases, using this class can adversely affect performance because creating an Iterator object might take longer than iterating over small collections. In many cases, Iterators do nothing except move parts of a for loop into a class.
class ArrayIterator {
ArrayIterator(int[] array) {
this.array = array;
index = 0;
}
boolean hasNext() {return index < array.length;}
int next() {
if(hasNext()) {
int current = array[index];
index++;
return current;
}
else
throw an exception
}
}
This class is probably the worst use of an Iterator ever because arrays can be iterated over more simply without the class. It is, however, an example that is easy to understand.
Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.