Java Reference
In-Depth Information
[Oracle 2013c]
Java Platform Standard Edition 7 Documentation
47. Prefer using iterators over enumerations
According to the Java API Interface Enumeration<E> documentation [API 2013],
Anobjectthatimplementsthe Enumeration interfacegeneratesaseriesofelements,
one at a time. Successive calls to the nextElement method return successive ele-
ments of the series.
As an example, the following code uses an Enumeration to display the contents of a
Vector :
Click here to view code image
for (Enumeration e = vector.elements(); e.hasMoreElements();) {
System.out.println(e.nextElement());
}
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 se-
mantics when elements in a collection are removed while iterating over the collection.
Consequently, iterators rather than enumerators should be preferred when examining iter-
able collections.
Noncompliant Code Example
This noncompliant code example implements a BankOperations class with a removeAc-
counts() 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, compar-
ing each entry with the name “Harry.”
Click here to view code image
class BankOperations {
private static void removeAccounts(Vector v, String name) {
Enumeration e = v.elements();
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
Search WWH ::




Custom Search