Card 05/ 08

GotchaDifficulty: Intermediate1 min

Why Map Is Not a Collection

You write a method that takes a Collection so it can accept anything, and hand it a Map. The compiler refuses, and the error reads as though Map were some unrelated type.

text
Report.java:9: error: incompatible types: Map<String,Order> cannot be converted to Collection<Order>

Collection is an interface about elements: one add(E), one contains(E), an iterator that hands you one element at a time. A map holds pairs, so none of those signatures fit — add would need two arguments, and it is not obvious what iterating should produce.

What a map offers instead is three views, each of which is a collection, and each of which is a live window rather than a copy.

The three collection views a map offers
ViewTypeHolds
map.keySet()Set<K>Every key, each once
map.values()Collection<V>Every value, duplicates and all
map.entrySet()Set<Map.Entry<K, V>>Both together, which is what you usually want

Iterate with entrySet() rather than looping over keys and calling get on each. The keys-and-get version does a second lookup per element for no reason, and it reads as though the two halves might disagree.