Java 如何创建通用 HashMap 来插入集合和对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20662279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Can I create a generic HashMap to insert collections and objects?
提问by user2683519
How Can I instantiate a HashMap to put collections and objects?.
如何实例化 HashMap 以放置集合和对象?。
//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);
采纳答案by Dirk
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.
事实上,只要方法只尝试从地图中读取。
回答by Prabhakaran Ramaswamy
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.
但是将所有类型的对象放入单个地图中并不是一个好习惯。更好的是,您可以创建 POJO 并将其添加到地图中。
回答by bmanvelyan
All classes in Java extends Object. so you can use Object for a value type in a map, like
Java 中的所有类都扩展了 Object。所以你可以使用 Object 作为映射中的值类型,比如
Map<String, Object> params = new HashMap<String, Object>
回答by hitesh
I cam here for substitute in Kotlin
我来这里是为了替代 Kotlin
You can declare in kotlin as :-
您可以在 kotlin 中声明为:-
val map: Map<String, Any?>