Web / Apache Commons Collections Interview questions
How is UnmodifiableMap in Commons Collections different from java.util's Collections.unmodifiableMap?
Functionally, both wrap an existing Map and throw UnsupportedOperationException on any mutating call - put(), remove(), clear() - while still being a live read-through view: changes made to the original backing map are visible through the wrapper.
| Collections.unmodifiableMap() | Commons Collections MapUtils.unmodifiableMap() |
| JDK-only, part of java.util.Collections | part of the wider Commons Collections decorator family |
| no shared marker interface for detecting immutability | implements the Unmodifiable marker interface |
| only covers Map/List/Set/Collection | equivalent decorators exist for Bag, BidiMap, and MultiValuedMap too |
The practical difference that matters most in larger codebases is the Unmodifiable marker interface: Commons Collections utilities can programmatically check instanceof Unmodifiable before deciding whether to wrap something again, avoiding redundant double-wrapping - a check the JDK's version gives you no clean way to perform.
More Related questions...