List.of, Set.of and Map.of rules
The map's entries are read with get, not printed: Map.of's iteration order is deliberately unspecified.
List.of, Set.of and Map.of (Java 9) create collections that can never change, and List.copyOf (Java 10) makes a frozen copy. Collections.unmodifiableList is different: a read-only view that still shows changes made to the original list underneath.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create an immutable map of three country codes to dial codes with Map.ofEntries and print one lookup.
Write a method that returns a sorted, immutable copy of any List<String> without changing the input.
Show that List.of(builder) is only shallowly immutable by changing the StringBuilder inside it.
Explain it without notes
What is the difference between an immutable list and an unmodifiable view?
Why do List.of and Map.of reject nulls, and what other strict rules do they have?
When would you return Collections.unmodifiableList and when List.copyOf from a getter?
Expected output
[Mon, Tue, Wed] size 3
add -> UnsupportedOperationException
List.of with null -> NullPointerException
Set.of duplicate -> duplicate element: x
pen: 10, ink: 4
contains Fri? false