[Java] Don't try to modify unmodifiable collections

Hi, I would like to propose the following new rule:

Unmodifiable collections cannot be modified.

This rule warns about code that attempts to modify an unmodifiable collection.
Keeping the code as it is will result in a java.lang.UnsupportedOperationException.

Noncompliant code examples

List<String> fruits = List.of("apple", "orange");
// ...
int size = fruits.size(); // Compliant
fruits.add("pear");       // Noncompliant; throws runtime exception
fruits.clear();           // Noncompliant; throws runtime exception
Map<String, String> colorsMap = Map.of("sky", "blue", "cloud", "white", "tree", "green");
// ...
colorsMap.putIfAbsent("banana", "yellow");   // Noncompliant; runtime exception here

Compliant code example

List<String> fruits = new ArrayList<>(List.of("apple", "orange"));
fruits.add("pear"); // Compliant; list is modifiable
  • external references and/or language specifications:

The rule should detect all cases where any mutator method is called on an instance that is known to have been created by one of the
java.util.Collections.unmodifiable*, java.util.Collections.empty* or java.util.Collections.singleton* methods or by one of the of(), copyOf(), ofEntries() static factory methods.

  • type : Bug