A list is walked backwards by index only to read its elements, which a loop over reversed() does without indexes
What it finds
for (int i = list.size() - 1; i >= 0; i--) use(list.get(i)); manages an index only to read the elements from the end. Since Java 21, for (T item : list.reversed()) does the same with nothing to get wrong.
Reported is a for loop that starts its index at size() - 1 of a list, counts down to 0 and uses the index only in get of that list.
Files whose build file (pom.xml, build.gradle or build.gradle.kts) compiles for a Java before 21 are left alone.
From the rule's source, reverse_index_loop.rs.
import java.util.List; class Backwards { void run(List<String> items) { for (int i = items.size() - 1; i >= 0; i--) {tx0 reports: reversed() would do it use(items.get(i)); } for (int i = items.size() - 1; i >= 0; i--) { use(i + items.get(i)); } } void use(String s) {}} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:reverse-index-loop" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:reverse-index-loop] reason="..."tx0 explain tx0/java:reverse-index-loop shows the same in the terminal. Found a false positive? Report it.