Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

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>

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.

I cam here for substitute in Kotlin

You can declare in kotlin as :-

val map: Map<String, Any?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top