Video in progress

Strong Middle 🧱 OOP and SOLID

Calling `add()` on a list returned by `List.of(...)` throws `UnsupportedOperationException`. Isn't that a Liskov violation?

Formally, yes, it contradicts LSP: the List contract promises add, but the implementation refuses it. The JDK documents this as an "optional operation", a deliberate trade-off.

📖 Answer

In the javadoc of java.util.List, methods like add, remove and set are marked "optional operation". The contract itself says "this method may throw UnsupportedOperationException". So from the JDK's point of view LSP is not formally broken: the contract is just weakly written.

In practice, though, the problem looks exactly like an LSP violation:

void addDefault(List<String> roles) {
    roles.add("USER"); // blows up at runtime if List.of(...) comes in
}

addDefault(new ArrayList<>(List.of("ADMIN"))); // works
addDefault(List.of("ADMIN"));                  // UnsupportedOperationException

The compiler says nothing, and the error only shows up in production. The designers of the Collections API chose this path because otherwise they would have needed dozens of interfaces like ReadableList, MutableList and FixedSizeList.

What to do in your own code:

  • if a method modifies its argument, say so in the name and the docs, or have it make its own copy: var copy = new ArrayList<>(roles);
  • if a method only reads, make the parameter type as general as you can: Collection<String> or Iterable<String>;
  • don't leave "optional" methods in your own interfaces. Split reading and writing into separate interfaces.

A good interview answer: "Technically the contract allows it, but it goes against the spirit of LSP and it's a conscious compromise in the JDK."