Elements are removed by index in a loop counting up, so the element after each removed one is skipped

tx0/java:index-removal-skips-elementdefaulterrorbug

What it finds

for (int i = 0; i < list.size(); i++) { if (bad(list.get(i))) list.remove(i); } skips an element after every removal: remove(i) shifts the following elements down by one, and i++ then steps over the one that moved into place i. The loop needs i-- after the removal, a descending loop, an iterator's remove, or removeIf, as the List.remove(int) documentation implies.

Reported is list.remove(i) inside a for loop that counts i up by one while i < list.size(), when the body does not change i and the removal is not followed in its block by break, return or throw, or by add(i, x) or set, which put an element back.

From the rule's source, remove_in_ascending_loop.rs.

Example from the rule's tests
import java.util.List; class Cleaner {  void clean(List<String> names) {    for (int i = 0; i < names.size(); i++) {      if (names.get(i).isEmpty()) {        names.remove(i);tx0 reports: the next element moves to the current index      }    }    for (int i = 0; i < names.size(); i++) {      if (names.get(i).isEmpty()) {        names.remove(i);        i--;      }    }    for (int i = 0; i < names.size(); i++) {      if (names.get(i).isBlank()) {        names.remove(i);        break;      }    }  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:index-removal-skips-element" = "off"

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:index-removal-skips-element] reason="..."

tx0 explain tx0/java:index-removal-skips-element shows the same in the terminal. Found a false positive? Report it.