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?
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.
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.
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.
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).
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)
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With