Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Map not extend Collection interface [duplicate]

Why doesn't java.util.Map interface extend the java.util.Collection interface? Isn't a java.util.Map a collection of Key-Value pairs?

like image 358
Swaranga Sarma Avatar asked Apr 18 '11 08:04

Swaranga Sarma


People also ask

Why are maps not part of the collection hierarchy?

The Map can not have such a method because it needs key-value pair. There are other reasons also such as Map supports EntrySet etc. Collection classes do not have such views. Due to such big differences, the Map interface was not included in the Collection framework hierarchy, and it was built in a separate hierarchy.

Why does not the Map interface extend the Collection interface?

Because they are of an incompatible type. List, Set and Queue are a collection of similar kind of objects but just values where a Map is a collection of key and value pairs.

Is Map a child interface of collection?

7) Map(Interface): Map is not the child interface of Collection. If we want to represent a group of objects as key-value pairs then we should go for a map. Both keys and values are objects only duplicate keys are not allowed but values can be duplicated.

Why is a Map different from a collection?

Because a Map is not a true collection, its characteristics and behaviors are different than the other collections like List or Set. A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null value (HashMap and LinkedHashMap) but some does not (TreeMap).


2 Answers

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)

like image 195
Peter Lawrey Avatar answered Sep 22 '22 11:09

Peter Lawrey


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().

like image 36
Henning Avatar answered Sep 23 '22 11:09

Henning