Johanna
Johanna

Reputation: 27660

collection and map

can we make a collection that implements map?thanks.

Upvotes: 1

Views: 472

Answers (4)

Gladwin Burboz
Gladwin Burboz

Reputation: 3549

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)

Upvotes: 1

helios
helios

Reputation: 13841

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.

Upvotes: 1

Yishai
Yishai

Reputation: 91931

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.

Upvotes: 2

Thomas Owens
Thomas Owens

Reputation: 116197

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.

Upvotes: 4

Related Questions