London
London

Reputation: 15274

Map inside map in java

What is wrong with this instantiation :

Map<String, String, HashMap<String,String>> map = new HashMap<String, String, HashMap<String,String>>();

Upvotes: 4

Views: 17476

Answers (4)

subbu
subbu

Reputation: 489

If you wish you can use something of this kind

Map<Object,Map<String,String>>

This object can be an object of a Class holding two Strings. Hope this solves your problem.

Class Xyz {
String s1;
String s2;
}

An object of Xyz can be used as key in the above map.

Upvotes: 1

polygenelubricants
polygenelubricants

Reputation: 383746

A Map<K,V> is a mapping from keys of type K to values of type V. There are only 2 type parameters to a map.

You attempted to define a map with 3 type parameters; this is not possible, and has nothing to do with the fact that you're putting a Map inside a Map.

A Map<K1,Map<K2,V2>> works just fine.

A Map<X,Y,Z> does not.

It's possible that you need something like Map< Pair<L,R>, Map<K,V> >. Java does not have generic Pair<L,R> type, but see related questions below for solutions.

Related questions

On pairs/tuples:

On nested maps:

Upvotes: 21

Eyal Schneider
Eyal Schneider

Reputation: 22446

Map interface (as well as HashMap class) expects only 2 generic type arguments: one for the key type and one for the value type. You provide 3...

Upvotes: 5

Mark Peters
Mark Peters

Reputation: 81074

Maps only have 2 type parameters, you have 3 (in your "outer" Map).

Upvotes: 5

Related Questions