Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

Java · Easy · Free

List.of, Set.of, Map.of (Java 9) — immutability and null rules?

JavaJava 8+Fresher
Model answer

Collection factories (Java 9)

List.of, Set.of, and Map.of create immutable collections with compact implementations. They reject null keys and values—fail fast at creation.

  • Map.of(k1,v1,k2,v2) limited to 10 entries; use Map.ofEntries for more.
  • Iteration order fixed for maps (insertion order of pairs).
  • Mutating methods throw UnsupportedOperationException.
  • Prefer over Arrays.asList when you need true immutability.
java
List<String> tags = List.of("java", "k8s");
Map<String, Integer> scores = Map.of("alice", 10, "bob", 8);
// scores.put("c", 1); // UnsupportedOperationException
Contrast List.of vs Collections.unmodifiableList—factory methods are deeply immutable.