Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed to Applicabiloity and updated the references to Java 7

According to the Java API [API 20062011], interface Enumeration Interface Enumeration<E> documentation,

An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.

...

Unfortunately, a Vector and an Enumeration may not always work well together. In fact, the Java API API [API 20062011] recommends, "New implementations should consider using Iterator in preference to Enumeration."

...

According to the Java API [API 20062011], interface Iterator Interface Iterator<E> documentation,

Iterator takes the place of Enumeration in 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.

...

Code Block
bgColor#ccccff
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"); 
  }
}

...

Applicability

Using Enumeration when performing remove operations on a vector may cause unexpected program behavior.

...

Guideline

...

Severity

...

...

Remediation Cost

...

Priority

...

Level

...

MSC61-JG

...

low

...

unlikely

...

medium

...

P2

...

L3

Automated Detection

The Coverity Prevent Version 5.0 ITERATOR checker can detect the instance where next() or previous() on an iterator is called that may not have a next or previous element.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

[API 20062011] Interfaces : Enumeration Enumeration<E> and Iterator Iterator<E>
[Daconta 2003] Item 21: Use Iteration over Enumeration

...

Image Modified