Command Palette

Search for a command to run...

Back to the lesson: Topic 9.11 — Immutable and Unmodifiable Collections
Core Java · Example 2 of 3 Java 10+

Unmodifiable view vs immutable copy

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.

01

Create an immutable map of three country codes to dial codes with Map.ofEntries and print one lookup.

02

Write a method that returns a sorted, immutable copy of any List<String> without changing the input.

03

Show that List.of(builder) is only shallowly immutable by changing the StringBuilder inside it.

Explain it without notes

01

What is the difference between an immutable list and an unmodifiable view?

02

Why do List.of and Map.of reject nulls, and what other strict rules do they have?

03

When would you return Collections.unmodifiableList and when List.copyOf from a getter?

Unmodifiable view vs immutable copy Java 10+
Sign in to run this example in your browser.

Expected output

source: [a, b, c]
view:   [a, b, c]
copy:   [a, b]
view.add -> UnsupportedOperationException
copyOf an immutable list is the same object? true