Java Reference
In-Depth Information
if (s.equals(name)) {
v.remove(name); // Second Harry is not removed
}
}
// Display current account holders
System.out.println("The names are:");
e = v.elements();
while (e.hasMoreElements()) {
// Prints Dick, Harry, Tom
System.out.println(e.nextElement());
}
}
public static void main(String args[]) {
// List contains a sorted array of account holder names
// Repeats are admissible
List list = new ArrayList(Arrays.asList(
new String[] {"Dick", "Harry", "Harry", "Tom"}));
Vector v = new Vector(list);
removeAccount(v, "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 un-
changed, 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.
Compliant Solution
According to the Java API Interface
Iterator<E>
documentation [API 2013],
Iterator
takes the place of
Enumeration
in the Java collections framework. Iterat-
ors differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection dur-
ing the iteration with well-defined semantics.
Method names have been improved.
This compliant solution remedies the problem described in the noncompliant code ex-
ample and demonstrates the advantages of using an
Iterator
over an
Enumeration
: