A collection is filled in an anonymous subclass with an initializer block

tx0/java:anonymous-collection-subclassrecommendedwarningbug

What it finds

new HashMap<>() {{ put("a", 1); }} creates an anonymous subclass of HashMap only to run an initializer. Each use is a new class; inside an instance method it holds a hidden reference to the outer object, which keeps it alive and drags it into serialization; and equals of some collections then fails on the class check. Map.of or plain calls after creation do the same without a subclass.

Reported is an anonymous class of a collection or map whose body holds nothing but instance initializers.

From the rule's source, double_brace_initialization.rs.

Example from the rule's tests
import java.util.HashMap;import java.util.Map; class Defaults {  Map<String, Integer> make() {    Map<String, Integer> a = new HashMap<>() {tx0 reports: anonymous subclass of the collection      {        put("a", 1);      }    };    Map<String, Integer> b = new HashMap<>();    b.put("a", 1);    return a.isEmpty() ? b : a;  }}
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 from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:anonymous-collection-subclass" = "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:anonymous-collection-subclass] reason="..."

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