Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map inside map in java

Tags:

java

What is wrong with this instantiation :

Map<String, String, HashMap<String,String>> map = new HashMap<String, String, HashMap<String,String>>();
like image 425
London Avatar asked Nov 27 '22 06:11

London


2 Answers

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:

  • What is the equivalent of the C++ Pair<L,R> in Java?
  • Java generics Pair<String, String> stored in HashMap not retrieving key->value properly
  • A Java collection of value pairs? (tuples?)
  • Does Java need tuples?
  • How to return multiple objects from a Java method?

On nested maps:

  • Java: Spring Framework: Declaring Nested Maps
  • Java: How do you declare nested map in spring framework?
  • Map of Maps data structure
like image 144
polygenelubricants Avatar answered Nov 29 '22 19:11

polygenelubricants


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

like image 36
Mark Peters Avatar answered Nov 29 '22 20:11

Mark Peters