...
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}}."" |
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
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""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""Dick", "Harry""Harry", "Harry""Harry", "Tom""Tom"})); Vector v = new Vector(list); removeAccount(v, "Harry""Harry"); } } |
Compliant Solution
Wiki Markup |
---|
According to the Java API \[[API 06|AA. Java References#API 06]\], interface {{Iterator}} documentation: |
...
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""Dick", "Harry""Harry", "Harry""Harry", "Tom""Tom"})); Vector v = new Vector(list); remove(v,"Harry""Harry"); } } |
Risk Assessment
Using Enumerations
when performing remove operations on a vector may cause unexpected program behavior.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] Interfaces: Enumeration and Iterator \[[Daconta 03|AA. Java References#Daconta 03]\] Item 21: Use Iteration over Enumeration |
...
IDS01-J. Prefer using URIs to URLs 49. Miscellaneous (MSC) MSC04-J. Carefully design interfaces before releasing them