19

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93

5 Answers5

28

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)

rachana
  • 3,344
  • 7
  • 30
  • 49
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
20

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

Henning
  • 16,063
  • 3
  • 51
  • 65
4

Because some methods declared in Collections do not fit a Map interface and vice versa.

An example for the first is the add(Object) method of the Collections interface,
an example of the second is the put(K, V) of the Map interface.

There is simply no consistent way to sensibly implement add(Object) for a Map - is it a key, is it a value? The same is valid for put(K, V). What could possibly be a key in an ArrayList?

kostja
  • 60,521
  • 48
  • 179
  • 224
3

Why doesn't java.util.Map interface extend the java.util.Collection interface?

Map is a key/value pair whereas Collection is a collection of a group of objects stored in a structured manner and has a specified access mechanism. The reason why Map doesn't extend Collections interface is that add(E e); doesn't cater the key value pair like Map's put(K, V).

Also, what would Collection's iterator() method point to if Map had to extend it? The key's iterator or value's iterator?

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
1

All collections must implement a default constructor and another constructor that takes a collection as a parameter. You can't construct a map with any other collection other than a map.

Since Map imposes restrictions on the type of objects it can hold, you can't implement a map as a collection.

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
  • 1
    The two constructors are **not** a strict requirement: they apply only to *general-purpose* collections (i.e. not to specialized ones) and it's written as '*should* provide two "standard" constructors', so even for general-purpose collections it's not an absolute must. – Joachim Sauer Apr 18 '11 at 08:34