Inspectopedia 2024.3 Help

Immutable collection creation can be replaced with collection factory call

Reports java.util.Collections unmodifiable collection calls that can be converted to newer collection factory methods. These can be replaced with e.g. List.of() or Set.of() introduced in Java 9 or List.copyOf() introduced in Java 10.

Note that in contrast to java.util.Collections methods, Java 9 collection factory methods:

  • Do not accept null values.

  • Require unique set elements and map keys.

  • Do not accept null arguments to query methods like List.contains() or Map.get() of the collections returned.

When these cases are violated, exceptions are thrown. This can change the semantics of the code after the migration.

Example:

List<Integer> even = Collections.unmodifiableList( Arrays.asList(2, 4, 6, 8, 10, 2)); List<Integer> evenCopy = Collections.unmodifiableList( new ArrayList<>(list1));

After the quick-fix is applied:

List<Integer> even = List.of(2, 4, 6, 8, 10, 2); List<Integer> evenCopy = List.copyOf(list);

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

Java9CollectionFactory
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Java language level migration aids | Java 9

Use the Do not warn when content is non-constant option to report only in cases when the supplied arguments are compile-time constants. This reduces the chances that the behavior changes, because it's not always possible to statically check whether original elements are unique and not null.

Use the Suggest 'Map.ofEntries' option to suggest replacing unmodifiable maps with more than 10 entries with Map.ofEntries().

This inspection depends on the Java feature 'Collection factory methods', which is available since Java 9.

New in 2017.2

Inspection options

Here you can find the description of settings available for the Immutable collection creation can be replaced with collection factory call inspection, and the reference of their default values.

Only report when content is constant

Not selected

Suggest 'Map.ofEntries()'

Default: Selected

Inspection Details

By default bundled with:

IntelliJ IDEA 2024.3, Qodana for JVM 2024.3,

Can be installed with plugin:

Java, 243.23126

Last modified: 03 December 2024