Manual Reverse Iteration
ID |
java.manual_reverse_iteration |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style |
Description
Reports a for loop that walks a collection backwards with a ListIterator started at the collection’s own size(), instead of using the Java 21 Sequenced Collections reversed() view.
Rationale
The loop is correct, just more verbose than it needs to be on Java 21 and later: list.reversed() returns a live, reversed view of the same collection, letting a plain forward for-each express the same iteration.
// Works, but more code than the modern idiom needs
void renderQueueInReverse(List<String> queue) {
for (var cursor = queue.listIterator(queue.size()); cursor.hasPrevious();) {
var task = cursor.previous();
System.out.println(task);
}
}
Remediation
Iterate the collection’s reversed() view directly.
void renderQueueInReverse(List<String> queue) {
for (var task : queue.reversed()) {
System.out.println(task);
}
}
reversed() requires Java 21 or later. On an older source level the reported loop is still correct; only the suggested fix is not yet actionable.
|