According to the Java API \ [[API 2006|AA. References#API 06]\], interface {{ Wiki Markup Enumeration
}} documentation,
An object that implements the
Enumeration
interface generates a series of elements, one at a time. Successive calls to thenextElement
method return successive elements of the series.
...
Code Block |
---|
for (Enumeration e = vector.elements(); e.hasMoreElements();) { System.out.println(e.nextElement()); } |
Unfortunately, a {{ Wiki Markup Vector
}} and an {{Enumeration
}} may not always work well together. In fact, the Java API \ [[API 2006|AA. References#API 06]\] recommends, "New implementations should consider using {{Iterator
}} in preference to {{Enumeration
}}."
Noncompliant Code Example
...
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 1, causing the program to use "Tom" for the next (now final) comparison. As a result, the second "Harry" remains in the vector unscathed, having shifted to the second position in the vector.
Compliant Solution
According to the Java API \ [[API 2006|AA. References#API 06]\], interface {{ Wiki Markup Iterator
}} documentation,
Iterator
takes the place ofEnumeration
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.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Bibliography
...
\[[API 2006|AA. References#API 06]\] Interfaces: Enumeration and Iterator
\
[[Daconta 2003|AA. References#Daconta 03] \] Item 21: Use Iteration over Enumeration
...