10

How Can I instantiate a HashMap to put collections and objects?.

//it's wrong
Map<String,?>params=new HashMap<String,? >
List<Person> lstperson=getPerson();
params.put("person",lstperson);
params.put("doc",objectDoc);
params.put("idSol",new Long(5));
service.method(params);

//method

public void method(Map<String, ?> params);
Matt
  • 14,906
  • 27
  • 99
  • 149
user2683519
  • 747
  • 5
  • 11
  • 19

4 Answers4

26

Declare the hash map as

Map<String,Object> params = new HashMap<String,Object>();

You can keep the declaration of

public void method(Map<String, ?> params);

as it is, as long as the method only every tries to read from the map.

Dirk
  • 30,623
  • 8
  • 82
  • 102
6

All classes in Java extends Object. so you can use Object for a value type in a map, like

Map<String, Object> params = new HashMap<String, Object>
bmanvelyan
  • 149
  • 4
5

You need to change

Map<String,?>params=new HashMap<String,? > 

to like this

Map<String,Object>params=new HashMap<String,Object>()

But its not good practice to put all type of objects into single map. Better you can create POJO and add it to map.

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

I cam here for substitute in Kotlin

You can declare in kotlin as :-

val map: Map<String, Any?>
hitesh
  • 378
  • 4
  • 12