A collection from an unmodifiable or fixed-size factory is changed, which throws

tx0/java:immutable-collection-mutationdefaulterrorbug

What it finds

List.of(...), Collections.emptyList(), Collections.unmodifiableMap(...) and their kin return collections that throw an UnsupportedOperationException on every change. Arrays.asList returns a list of fixed size: it can set elements but not add or remove them. The documentation of each factory says so. A local variable that holds one of them and is changed later fails at that line.

Reported is a call that adds, removes, puts, sets, sorts or clears on a local variable that is initialized with one of these factories and never assigned again.

From the rule's source, immutable_collection_mutation.rs.

Example from the rule's tests
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.Map; class Lists {  void change(String name) {    List<String> names = List.of("a", "b");    names.add(name);tx0 reports: comes from List.of, which does not allow this change    List<String> fixed = Arrays.asList("a", "b");    fixed.set(0, name);    fixed.remove(name);tx0 reports: comes from Arrays.asList    Map<String, Integer> empty = Collections.emptyMap();    empty.put(name, 1);tx0 reports: comes from Collections.emptyMap    List<String> later = Collections.emptyList();    later = new ArrayList<>();    later.add(name);  }}
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:immutable-collection-mutation" = "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:immutable-collection-mutation] reason="..."

tx0 explain tx0/java:immutable-collection-mutation shows the same in the terminal. Found a false positive? Report it.