tags:

views:

99

answers:

4

hi, can we make a collection that implements map?thanks.

+4  A: 

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.

Thomas Owens
@Thomas - a toArray on the map would probably be a Map.Entry array. However, the remove point remains valid.
MetroidFan2002
True, but it is an ambiguous function on maps, IMO. Will it return an array so that i%2 == 0 are keys and i%2 == 1 are values? Or just values? Or just keys?
Thomas Owens
+1  A: 

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.

Yishai
+1  A: 

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.

helios
A: 

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)
Gladwin Burboz