Java / Java 21 Interview Questions
What are the immutable collection factory methods introduced in Java 9?
Java 9 (JEP 269) introduced convenient static factory methods on List, Set, and Map for creating small, immutable collections without the verbosity of Arrays.asList() or Collections.unmodifiableList().
// Java 9+ — concise and immutable
List list = List.of("a", "b", "c"); // immutable
Set set = Set.of(1, 2, 3); // immutable, no dups
Map map = Map.of("one", 1, "two", 2); // up to 10 pairs
Map bigMap = Map.ofEntries( // more than 10 pairs
Map.entry("a", 1),
Map.entry("b", 2)
);
// Copying (Java 10+)
List copy = List.copyOf(mutableList); // immutable copy
Set sCopy = Set.copyOf(existingSet);
// Java 9 vs Arrays.asList
// Arrays.asList: fixed-size but MUTABLE (set() works, add() throws)
// List.of: IMMUTABLE (set(), add(), remove() all throw)
list.add("d"); // UnsupportedOperationException
list.set(0, "z"); // UnsupportedOperationException
// Null not permitted in List.of / Set.of / Map.of
List.of("a", null, "c"); // NullPointerException at creation
// Set.of does not allow duplicates
Set.of(1, 2, 2); // IllegalArgumentException These factory-created collections are optimised for memory: small sets and maps use compact array-based implementations rather than hash tables when they have few elements. The iteration order of Set.of and Map.of is intentionally unspecified and may vary between JVM runs.
More Related questions...