According to the Java API, Interface Enumeration<E> documentation [API 2011], Interface Enumeration<E> documentation,
An object that implements the
Enumeration
interface generates a series of elements, one at a time. Successive calls to thenextElement
method return successive elements of the series.
As an example, an Enumeration
is used in the following code to display the contents of a Vector
.:
Code Block |
---|
for (Enumeration e = vector.elements(); e.hasMoreElements();) { System.out.println(e.nextElement()); } |
Unfortunately, a Vector
and an Enumeration
may not always work well together. In fact, the Java API [API 2011] recommends, "New implementations should consider using Iterator
in preference to Enumeration
." . Consequently, iterators rather than enumerators should be preferred when examining iterable collections.
...
According to the Java API, Interface Iterator<E> documentation [API 2011], Interface Iterator<E> documentation,
Iterator
takes the place ofEnumeration
in the Java collections framework. Iterators differ from enumerations in two ways:
- Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
- Method names have been improved.
This compliant solution remedies the problem described in the noncompliant code example and demonstrates the advantages of using an Iterator
over an Enumeration
.:
Code Block | ||
---|---|---|
| ||
class BankOperations { private static void removeAccounts(Vector v, String name) { Iterator i = v.iterator(); while (i.hasNext()) { String s = (String) i.next(); if (s.equals(name)) { i.remove(); // Correctly removes all instances of the name Harry } } // Display current account holders System.out.println("The names are:"); i = v.iterator(); while (i.hasNext()) { System.out.println(i.next()); // Prints Dick, Tom only } } public static void main(String args[]) { List list = new ArrayList(Arrays.asList( new String[] {"Dick", "Harry", "Harry", "Tom"})); Vector v = new Vector(list); remove(v, "Harry"); } } |
...
Using Enumeration
when performing remove operations on a vector may cause unexpected program behavior.
Bibliography
[API 2011] |
...
Interface Enumeration<E> |
...
Interface Iterator<E> | |
[Daconta 2003] | Item 21 |
...
, "Use Iteration over Enumeration" |
...