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

Nested Collections: Shallow Protection

Recognize that unmodifiable wrappers only protect the top-level collection, not nested or contained mutable objects.

Nested Collections: Shallow Protection

What you'll learn: You'll understand that Collections.unmodifiable...() wrappers only protect the outer collection structure, not the objects inside it.


The Surface-Level Lock

When you wrap a collection with Collections.unmodifiableList() or similar methods, Java protects the structure of that collection—you can't add, remove, or replace elements. However, if your collection contains mutable objects (including other collections), those inner objects remain fully modifiable.

Think of it like a locked display case: you can't rearrange the items on the shelf, but if one of those items is an unlocked box, you can still open it and change what's inside.

Why This Matters

Consider an unmodifiable list containing regular ArrayList objects:

List<List<String>> original = new ArrayList<>();
original.add(new ArrayList<>(Arrays.asList("a", "b")));

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

// This fails - can't modify the outer list structure:
// unmodifiable.add(new ArrayList<>());  // UnsupportedOperationException

// But this works - the inner list is still mutable!
unmodifiable.get(0).add("c");  // Succeeds!
System.out.println(unmodifiable.get(0));  // [a, b, c]

The outer list is protected, but the ArrayList at index 0 is the same mutable object as before. The wrapper doesn't create a deep copy or make nested collections unmodifiable.

The Solution Pattern

If you need true immutability with nested collections, you must wrap every level:

List<List<String>> inner = Collections.unmodifiableList(Arrays.asList("a", "b"));
List<List<String>> outer = Collections.unmodifiableList(Arrays.asList(inner));

Key Takeaway: Unmodifiable wrappers provide shallow protection—only the direct structure is protected, not nested or contained mutable objects. Always consider whether inner collections need wrapping too.