Web / Apache Commons Collections Interview questions
What is the difference between a Map and a MultiValuedMap?
A standard Map<K,V> associates exactly one value with each key - calling put() a second time on the same key overwrites the first value. A MultiValuedMap<K,V> associates each key with a Collection of values, so repeated put() calls accumulate rather than overwrite.
| Map<K,V> | MultiValuedMap<K,V> |
| get(key) returns a single V | get(key) returns a Collection<V> |
| put() overwrites the existing value | put() adds to the existing values |
| part of java.util | defined by Commons Collections, not extending java.util.Map |
There's a subtle design reason MultiValuedMap deliberately doesn't extend java.util.Map: Map's contract says get(key) returns V, but a multi-value map needs to return Collection<V> - trying to satisfy both signatures at once breaks Java's generics type safety, which is exactly what the legacy 3.x MultiMap ran into by extending Map with a raw Object return type.
More Related questions...