Exceptions: List.of and Map.of throw UnsupportedOperationException on any mutation

The collections returned by List.of and Map.of are truly immutable, not just unmodifiable views; calling add, remove, put or any other mutator on them throws UnsupportedOperationException every time.

Code
List<String> fixed = List.of("a", "b", "c");
try {
    fixed.add("d");
} catch (UnsupportedOperationException e) {
    System.out.println("List.of add: " + e.getClass().getSimpleName());
}
Map<String, Integer> fixedMap = Map.of("x", 1);
try {
    fixedMap.put("y", 2);
} catch (UnsupportedOperationException e) {
    System.out.println("Map.of put: " + e.getClass().getSimpleName());
}
Output
List.of add: UnsupportedOperationException
Map.of put: UnsupportedOperationException
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms