Course contentsShow
← Java
Lesson 1241 of 2,87028. Collections Utility ClassFree lesson

Unmodifiable Views Are Not Immutable

Understand that unmodifiable views reflect changes to the backing collection, making them mutable despite restricted access.

Unmodifiable Views Are Not Immutable

You'll learn why an unmodifiable collection can still change despite being "read-only."

When you create an unmodifiable view using methods like Collections.unmodifiableList(), you might think you've created an immutable collection—one that never changes. This is a critical misconception. Unmodifiable views only prevent you from modifying the collection through that specific view. They don't prevent changes to the original backing collection.

The Core Difference

Think of it like a glass display case in a museum. You can look at the artifacts inside, but you can't touch them through the glass (unmodifiable). However, museum staff with keys can still add, remove, or rearrange items from behind the scenes (the backing collection). When they do, you immediately see those changes through the glass.

How It Works

When you create an unmodifiable view, Java doesn't copy the data—it creates a wrapper around the original collection. Any changes made to the original collection are instantly visible through the unmodifiable view because they both reference the same underlying data.

List<String> original = new ArrayList<>();
original.add("Apple");
original.add("Banana");

List<String> unmodifiable = Collections.unmodifiableList(original);

System.out.println(unmodifiable); // [Apple, Banana]

// Modify the original
original.add("Cherry");

System.out.println(unmodifiable); // [Apple, Banana, Cherry]
// The unmodifiable view reflects the change!

Key Takeaway: Unmodifiable views prevent modifications through that specific reference, but they reflect any changes made to the backing collection—they are read-only views, not truly immutable snapshots.