An object that implements the
Enumerationinterface generates a series of elements, one at a time. Successive calls to the
nextElementmethod return successive elements of the series.
As an example, the following code uses an
Enumeration to display the contents of a
The Java API [API 2013] recommends, "New implementations should consider using
Iterator in preference to
Enumeration." Iterators are superior to enumerations because they use simpler method names, and unlike enumerations, iterators have well-defined semantics when elements in a collection are removed while iterating over the collection. Consequently, iterators rather than enumerators should be preferred when examining iterable collections.
Noncompliant Code Example
This noncompliant code example implements a
BankOperations class with a
removeAccounts() method used to terminate all the accounts of a particular account holder, as identified by the name. Names can be repeated in the vector if a person has more than one account. The
remove() method attempts to iterate through all the vector entries, comparing each entry with the name "Harry."
Upon encountering the first "Harry," it successfully removes the entry, and the size of the vector diminishes to three. However, the index of the
Enumeration remains unchanged, causing the program to perform the next (now final) comparison with "Tom." Consequently, the second "Harry" remains in the vector unscathed, having shifted to the second position in the vector.
Iteratortakes the place of
Enumerationin 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 when performing remove operations on an iterable
Collection may cause unexpected program behavior.
|[API 2013]||Interface Enumeration<E>|
|[Daconta 2003]||Item 21, "Use Iteration over Enumeration"|