开发者

collection and map

can we make a collection 开发者_StackOverflow中文版that implements map?thanks.


A map is, by definition, a "collection". However, if you implement the Map interface, you will not have a subclass of Collection as the Map interface does not extend the Collection interface. The reason for this is that maps work on key-value pairs, while collections are just single objects grouped together.

There are also some conflicts between the Map and Collection interfaces. For example, you would have to have a implementation of toArray, which to me, doesn't make sense on a map. In addition, the remove methods have different signatures.


There are two ways to understand the question.

At a technical level, can a class implement both interfaces simultaneously? No, because the remove method is incompatible between the two interfaces (one returns Object, the other boolean).

At a conceptual level, the Map.EntrySet of the Map is kind of the Collection representation of the Map, so you might be able to leverage it when you need a Collection.

If you just want a Collection of the values in the Map, just use Map.values() method.


Yes, you can implement two diferent interfaces with a single class. Edit: except for the incompatibility in the remove method. (thanks Thomas)

But, in this case you can use some implementation of Map and use the fact that Map.entrySet(), Map.keySet() and Map.values() return an entries, keys and values collection respectivelly.

It depends what you can access and how, the collection that you are interested in.

If you need ordered access to the keyset probably you should use a TreeMap, that keeps and ordered tree of the keys.


This is not possible due to incompatiblity with return type in remove method on Collection and Map interface having same signature.

.

Return type is boolean

java.util.Collection
public boolean remove(Object o)

.

Return type is java.lang.Object

java.util.Map
public Object remove(Object key)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜