Skip to main content

Unmodifiable Views vs Immutable Copies

intermediate12 min readLesson 77 of 180

The difference between a read-only view and an independent copy โ€” and the Arrays.asList trap.

Unmodifiable views vs immutable copies

Three different "cannot change" guarantees:

List<String> src = new ArrayList<>(List.of("a", "b"));

List<String> view = Collections.unmodifiableList(src);
// view.set(0, "x") throws โ€” but src.set(0, "x") changes the view too!

List<String> copy = List.copyOf(src);
// copy is independent: mutating src cannot reach it

List<String> literal = List.of("a", "b");
// immutable since birth, no copy cost, rejects nulls

List.of/Set.of/Map.of are the default for constants. List.copyOf is the tool for sealing caller-provided collections. Unmodifiable views are for controlled exposure โ€” the owner keeps mutability, the caller doesn't get it.

Arrays.asList is a trap: fixed-size but writable โ€” set works, add throws. Rarely what you mean.

Now practice

Collections LabComparator composition, heap scheduling with stable ties, and sealed vs live collection exposure.3 challenges ยท ยท ~40 min