Defensive Copying vs Unmodifiable Views
You'll learn how defensive copying and unmodifiable views protect collections differently, and when to choose each approach.
Both defensive copying and unmodifiable views prevent external code from modifying your collections, but they use fundamentally different strategies with distinct trade-offs.
The Core Difference
Defensive copying creates a brand-new, independent collection containing copies of the original elements. Changes to the original don't affect the copy, and vice versa. Think of it like photocopying a document — you now have two separate papers.
Unmodifiable views wrap the original collection and block modification methods. The view shares the same underlying data. Think of it like putting a document in a locked display case — you can see it, but you can't change it. However, if someone with the original document edits it, you'll see those changes through the glass.
Performance Trade-offs
Defensive copying has higher upfront cost (time and memory to duplicate elements) but provides complete isolation. If your collection has 10,000 elements, you're duplicating all 10,000.
Unmodifiable views have minimal overhead — just a thin wrapper object. Perfect when you want to expose data without copying, especially for large collections.
Safety Trade-offs
Defensive copies are truly independent. Modifications to the original collection don't leak through.
Unmodifiable views provide weaker guarantees. If the backing collection changes, those changes appear in the view. Also remember: they offer shallow protection. If your collection contains mutable objects, those objects can still be modified.
When to Use Each
Use defensive copying when you need complete isolation between internal state and external code, or when working with untrusted code.
Use unmodifiable views when performance matters, you control the backing collection, and you just need to prevent accidental modifications through the returned reference.
Key Takeaway: Defensive copying creates independent duplicates for complete isolation but costs memory/time; unmodifiable views provide lightweight read-only access but share the underlying data, making them faster but less isolated.