Card 05/ 08

GotchaDifficulty: Intermediate1 min

Why Map Is Not a Collection

A Map holds pairs, so it cannot be passed where a Collection is expected, and offers three views instead.

Map does not extend Collection, because Collection describes single elements and a map holds key and value pairs. A method that accepts any Collection therefore refuses a Map, and the map offers three collection views of itself instead.

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 an unrelated type:

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

Collection is an interface about elements: a one-argument add(E), contains(E), and an iterator, an object that hands you one element at a time. None of those fit pairs: 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 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.