Learnitweb

Why Map interface doesn’t extend Collection interface?

This is because the two interfaces have a very different semantics. Following points can be provided to support this:

  • Collection is a collection of objects whereas Map is a collection of key value pairs.
  • Few methods implemented by Collection interface are incompatible with Map interface. For example add(Object) method of Collection is logically incompatible with Map. What will this method mean for a Map? Add a key or add a value?
  • Same applies to methods which are used to remove elements. For a collection it means to remove an element. But what will it mean for a Map? Remove a key or remove a value?
  • Collection’s iterator returns iterator over values. If HashMap would have extended Collection, what would iterator over a Map return? Iterator over keys or values?
  • All collections provide constructor which accepts another collection. Thus we can create a particular type of collection using a different type of collection. This is because a Collection is a collection of single values. But in case of Map it will not be possible. What will this constructor now create from a Map? A collection of keys or collection of values?