Vince
Vince

Reputation: 15156

Why is a Map not a "true" collection?

I came across this in the Java Collections tutorial:

"Note also that the hierarchy consists of two distinct trees — a Map is not a true Collection."

This confuses me, as I always thought a Map was a collection. Can anyone shine some light on what this means?

What is a "true" collection and why is a Map not one of them?

Upvotes: 0

Views: 161

Answers (3)

rachana
rachana

Reputation: 3424

Map is not a true Collection.Because the Collection interface is largely incompatible with the Map interface. If Map extended Collection, what would the add(Object) method do?

The two interfaces have very different semantics. If you need the values or the keys of a Map as collections, you can always use keySet()/values().

Please refer Java Collections API Design FAQ:

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Map is not a true Collection because it doesn't extend the Collection interface. Besides that, it is a collection by concept.

Upvotes: 9

AlexR
AlexR

Reputation: 115378

Map is an association between keys and values. Other (true) collections are ... collections of similar values. It is almost impossible to consolidate so different data structures under the same interface. This is the reason why Collections implement interface Colletion and maps implement interface Map.

Upvotes: 0

Related Questions