Avoid Enumeration For Loop Control
ID |
java.loop_legacy_enumeration |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Java |
Tags |
efficiency |
Description
Reports the use of java.util.Enumeration as the driver of a while or do-while loop — the classic while (e.hasMoreElements()) { e.nextElement(); } pattern.
Rationale
Enumeration predates the Collections framework and has been superseded in practical code by Iterator and Iterable:
-
it is not
Iterable, so it cannot be used with the enhancedfor-eachloop; -
it does not support element removal (
Iterator.remove()); -
method names (
hasMoreElements,nextElement) are verbose compared with the idiomatichasNext/next.
Most Enumeration-returning APIs expose an iterator() or a collection view. Using them lets the loop participate in standard idioms — for-each, forEachRemaining, streams.
// Bad — legacy Enumeration drives the loop
Enumeration<String> e = vector.elements();
while (e.hasMoreElements()) {
process(e.nextElement());
}
// Good — enhanced for-each over the collection
for (String s : vector) {
process(s);
}
// Good — Iterator when removal is needed
Iterator<String> it = vector.iterator();
while (it.hasNext()) {
if (isStale(it.next())) {
it.remove();
}
}
Remediation
Replace the Enumeration with an Iterator (via Collection.iterator()) or iterate directly with for-each when the receiver is Iterable. For legacy APIs that only expose Enumeration (e.g. NetworkInterface.getInetAddresses()), wrap it with Collections.list(…) and iterate the resulting list.