Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 549
user2683519 Avatar asked Dec 18 '13 15:12

user2683519


People also ask

How do you make a generic HashMap?

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.

How HashMap stores different data types?

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.

What is HashMap String object?

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.


2 Answers

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.

like image 136
Dirk Avatar answered Sep 24 '22 04:09

Dirk


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>
like image 22
bmanvelyan Avatar answered Sep 24 '22 04:09

bmanvelyan