...
Wiki Markup |
---|
Unfortunately, a {{Vector}} and an {{Enumeration}} may not always work well together, as demonstrated in the noncompliant code example. In fact, the Java API \[[API 06|AA. Java References#API 06]\] recommends, "New implementations should consider using {{Iterator}} in preference to {{Enumeration}}." |
...
This noncompliant code example implements a BankOperations
class with a removeAccounts()
method that is 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. Awkwardly, the index of the Enumeration does not decrease by one leading causing the program to use "Tom" for the next (now final) comparison. As a result, the second "Harry" continues to remain in the vector unscathed, having shifted to the second position in the vector.
...
This compliant solution remedies the aforementioned problem described in the noncompliant code example and confirms 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");
}
}
|
Risk Assessment
...