Yashasvi Raj Pant
Yashasvi Raj Pant

Reputation: 1424

How to create multimap of general datatype value in Java

I want to create a multimap where value could be general data type. For eg:

  MultiMap<String,Integer> columnvalueMapList = new MultiMap<String,Integer>();

Here instead of integer, i want to make general data type. How can i do so?

Upvotes: 1

Views: 112

Answers (1)

sprinter
sprinter

Reputation: 27966

You can use Object as a value type in a Map. However this is rarely a good idea as you will likely end up needing instanceof and casts to make use of the objects you extract.

Often the motivation for this is to be able to store objects of different classes without a common superclass. However a better option in these situations is to use an interface to define the common behaviour for all items in the collection. Then any classes that could be added to the collection must implement that interface. You then declare your collection as, for example, List<CommonInterface>. This is safer, clearer and easier to understand.

Upvotes: 4

Related Questions