A collection is changed inside an enhanced for loop over it
What it finds
for (String name : names) { if (name.isEmpty()) names.remove(name); } changes the collection that the loop is iterating over. The iterator of the standard collections notices on its next step and throws ConcurrentModificationException, or, when the change happens on the second to last element, the loop silently skips the rest. names.removeIf(...) or an explicit Iterator with iterator.remove() does it safely.
Reported are calls of add, addAll, remove, removeAll, removeIf, retainAll, clear and put on the iterated variable in the loop's body, unless the loop is left right after the call, by a break, return or throw later in the same block. Collections declared as, or initialized with, one of the concurrent or copy-on-write classes are left alone.
From the rule's source, modified_while_iterating.rs.
import java.util.List;import java.util.Map;import java.util.concurrent.CopyOnWriteArrayList; class Cleanup { void prune(List<String> names, Map<String, Integer> sizes) { for (String name : names) { if (name.isEmpty()) { names.remove(name);tx0 reports: remove changes names while the loop iterates over it } } for (String name : names) { if (name.isBlank()) { names.remove(name); break; } } for (String name : names) { sizes.put(name, name.length()); } CopyOnWriteArrayList<String> safe = new CopyOnWriteArrayList<>(); for (String name : safe) { safe.add(name); } }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:modified-while-iterating" = "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:modified-while-iterating] reason="..."tx0 explain tx0/java:modified-while-iterating shows the same in the terminal. Found a false positive? Report it.