开发者

Why does Map not extend Collection interface [duplicate]

This question already has answers here: Why doesn't Java Map extend Collection? (9 answers) Closed 8 years ago.

Why doesn't java.util.Map interface 开发者_如何学Goextend the java.util.Collection interface? Isn't a java.util.Map a collection of Key-Value pairs?


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


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?


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜