Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
for (Enumeration e = vvector.elements(); e.hasMoreElements();) {
  System.out.println(e.nextElement());
}

...

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. Awkwardly, the index of the Enumeration does not decrease by one 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.

Code Block
bgColor#FFcccc
class BankOperations {
  private static void removeAccounts(Vector v, String name) {
    Enumeration e = v.elements();
		 
    while (e.hasMoreElements()) {
      String s = (String) e.nextElement();
      if (s.equals(name)) {
        v.remove("Harry"); // Second Harry is not removed
      }
    }

    // Display current account holders
    System.out.println("The names are:");
    e = v.elements();
    while (e.hasMoreElements()) {
      System.out.println(e.nextElement());  // Prints Dick, Harry, Tom	  
    }
  }
	 
  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 does not decrease by one 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.

Compliant Solution

Wiki Markup
According to the Java API \[[API 06|AA. Java References#API 06]\], interface {{Iterator}} documentation:

...