It is frequently useful to be able to extract the elements of a vector, list, tree, graph etc. one at a time successively, and to do something with them. It might simply be to print them out to the screen or to a file. There is a standard way of approaching this problem in Java, which makes use of the Enumeration interface in the java.util package:
public interface Enumeration {
boolean hasMoreElements();
Object nextElement();
}
The hasMoreElements method of an enumeration returns true or false depending on whether or not the enumeration is exhausted. The nextElement method returns the next element in the enumeration, if there is a next element, so that successive calls to this method enumerate the elements. The nextElement method should throw a NoSuchElementException if there are no more elements to enumerate. An implementation of the Enumeration interface must implement these two methods.
Note that the Enumeration interface only specifies what an enumeration of a collection must provide. It is up to the implementer of that collection to actually provide it. The Vector class, however, in java.util does provide an enumeration method called elements. The following code will therefore enumerate the elements of a vector v.
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
This declares a variable e of type Enumeration and
assigns to it the enumeration obtained by calling the
elements method of the Vector class.
The enumeration e is tied to a particular vector v when it is initialised; there is no need for any further reference to the vector v. The enumeration e enumerates the elements of v sequentially by successive calls to e.nextElement. Note that you cannot change direction and enumerate backwards at some point. Nor can you make any change in a collection by means of the enumeration methods. Changes could be made to the collection, in the course of an enumeration, by some other methods. But this is dangerous. A specific danger lies in removing from the collection the item that happens to be the current one in the enumeration. In that case the results are unpredictable.