Tuesday, August 5

Why Map dosen't implement Collection Interface?

Why doesn't Map extend Collection?

Reson 1)

Collection assume elements of one value. Map assumes entries of key/value pairs. They could have been engineered to re-use the same common interface however some methods they implement are incompatible e.g.
Collection.remove(Object) - removes an element.
Map.remove(Object) - removes by key, not by entry.

You could model a Map as a collection of entries, which is what Map.entrySet() does.

There are some methods in common; size(), isEmpty(), clear(), putAll/addAll() but these are unlikely to have much value as a stand alone interface. (Again Map.entrySet() can be used instead)

 

 Reson 2)

This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa).



    If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to.

    Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface.

    Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That's why we don't have a map view operation on Lists.

2 comments:

Ads Inside Post