What Are Unmodifiable Collections?
You'll learn what unmodifiable collections are, how they differ from truly immutable collections, and why they're essential for safe API design.
The Core Concept
An unmodifiable collection is a read-only view of an existing collection. When you create an unmodifiable collection, you get a wrapper that blocks all modification attempts—calling add(), remove(), or clear() throws an UnsupportedOperationException. However, if the underlying original collection changes, those changes are visible through the unmodifiable view.
Think of it like a museum display case: you can look at the artifacts inside, but the glass prevents you from touching them. However, if a curator removes an item from the back, you'll notice it's gone when you look again.
Unmodifiable vs Immutable
This is a crucial distinction:
- Unmodifiable: A view that prevents you from making changes, but the underlying collection can still change
- Immutable: The collection itself cannot change, period—no matter who has a reference to it
An unmodifiable collection is like a read-only access level. True immutability means the data is frozen forever.
Why It Matters for API Design
When designing classes, you often want to expose internal collections without allowing external code to modify them. Returning an unmodifiable view protects your class's internal state while still letting clients read the data. Without this, anyone with a reference could corrupt your carefully managed collection.
Key Takeaway: Unmodifiable collections provide read-only views that prevent modification attempts but still reflect changes to the underlying collection—they're essential for defensive API design but aren't the same as truly immutable collections.