繁体   English   中英

创建哈希图时正确使用泛型

[英]correct usage of generics while creating hashmap

我有一个hashMap,其中键是String,值可以是Integer或long。 现在在一个方法中,我正在创建此HashMap并将类似的内容传递给其他方法

methodA(long a,Integer b)

{
Map<String,? super Number> hm = new HashMap<>();
hm.put("key1",a);
hm.put("key2",b);

invokeMethodC(hm);
}

invokeMethodC(Map<String, ?> uriVariables)
{
....
}

只想知道我在创建hashMap对象时是否使用了正确的泛型

不要使用extends / super,因为您将无法在地图中放置元素,这会导致编译错误

Map<String, Number> uriVariables = = new HashMap<>();

Map<String,? super Number> Map<String,? super Number>将在get()上返回Object。 最好使用Map<String, Number>然后put()将接受Long和Integer,而get()将返回Number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM