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);
use generics. Generic Map in simple language can be generalized as: Map< K, V > map = new HashMap< K, V >(); Where K and V are used to specify the generic type parameter passed in the declaration of a HashMap.
4.2. First, let's see how to declare the Map and put various types' data in it: Map<String, DynamicTypeValue> theMap = new HashMap<>(); theMap. put("E1 (Integer)", new IntegerTypeValue(intValue)); theMap. put("E2 (IntArray)", new IntArrayTypeValue(intArray)); theMap.
Java HashMap is a hash table based implementation of Java's Map interface. A Map, as you might know, is a collection of key-value pairs. It maps keys to values. Following are few key points to note about HashMaps in Java - A HashMap cannot contain duplicate keys.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With