Java Reference
In-Depth Information
Note several things about the loop in this method. First, each iteration
processes two elements of the enumeration, appending the first to res and throw-
ing the second away (if it exists). Second, the character to be appended to res is
cast to class Character , as required. Third, nextElement is called only if it is
known that a next element exists.
A method to print any enumeration
Earlier, we wrote a method to print the characters of a String using a
StringEnumeration . Below, we rewrite this method to print any enumeration,
using the fact that toString is defined on all objects. Instead of a String , the
parameter is an Enumeration :
/** Print enumeration e */
public static void print(Enumeration e) {
while (e.hasMoreElements())
{ System.out.println(e.nextElement()); }
}
We give a simple example of the use of method print :
print( new StringEnumeration(" abcde "));
Also, if a class ArrayEnumeration enumerates the elements of an array, we
can print the elements of an array b using:
print( new ArrayEnumeration(b));
Interface Iterator
Java 1.2 introduced interface java.util.Iterator (see Fig. 12.9) The
names of the methods are different, and there is a new method that allows the
removal of elements from the collection during the iteration.
public interface Iterator {
/** = the enumeration (or iteration) has more elements */
boolean hasNext();
/** = next element in the enumeration. Throw NoSuchException if there is none. */
Object next();
/** Remove the last element returned by method next() . Call remove at most once per
call to next . The behavior of an iterator is unspecified if the underlying collection is
modified while the iteration is in progress in any way other than by calling remove. If
remove is not supported, throw an UnsupportedOperationException .
If remove is called illegally (e.g. twice for one call of method next ), throw an
IllegalStateException . */
void remove ();
}
Figure 12.9:
Interface Iterator
Search WWH ::




Custom Search