How Can I create a generic HashMap to insert collections and objects?

73.2k views Asked by At

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);
4

There are 4 answers

1
Dirk On BEST ANSWER

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.

1
Prabhakaran Ramaswamy On

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.

0
bmanvelyan On

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>
0
hitesh On

I cam here for substitute in Kotlin

You can declare in kotlin as :-

val map: Map<String, Any?>