CS 531 LAB 1
Building an Iterator
Download files
Goal
Given a GenericWrapper.java, write an Iterator that implements java.util.Iterator and test it with TestGenericWrapper.java
What is an Iterator
The GenericWrapper has one particular disadvantage in practice. This is that there is not way to iterate over its contents.
Java provides the concept of an Iterator. An iterator provides a way to traversing the wrapper, visiting each of the elemnts in turn. The same concept can apply to other data types which are essentially collections of elements- lists, stacks, queus, maps,...
The java.util package (from Java 1.2 onwards) provides an Iterator interface which is used by some of the Java Collection Classes. The Iterator interface will be used in writing our IteratorClass today at the lab.
Java Iterator Interface
The java.util.iterator interface simply definies three methods:
- public boolean hasNext(), returns true if the iteration has more elements
- public Object next(), returns the next element in the iteration
- public void remove(), removes the last element returned by the iterator
What you have to do
By convention GenericWrapper does not implement java.util.iterator directly(although it could), so he methods hasNext(), next() and remove() are not GenericWrapper instance methods. Instead an ArrayWrapperIterator class should be defined to implement Iterator interface, and a method -by convention called iterator() - in GenericWrapper to return a new iterator.
So basically what you have to do:
- (in GenericWrapper class)implement an iterator() that will create and return a new instance of ArraywrapperIterator that can be used to iterate over all elements of the GenericWrapper
- (in ArrayWrapperIterator class)get the next object in the sequence with next()
- (in ArrayWrapperIterator class)check if there are any more objects in the sequence with hasNext()
- (in ArrayWrapperIterator class)remove the last element returned by an iterator with remove()
caveat
Any number of iterators can simultaneosuly traverse the same GenericWrapper. Hower, care must be taken in this case since the use of the remove() method could have side-effects. The remove() method can be invokd once, and only once, after invoking the next() method. It deletes from the GenericWrapper element just returned by next(). In all other cases using the remove() method will cause an exception.