有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在创建hashmap时正确使用泛型

我有一个hashMap,其中键是字符串,值可以是整数或长。 现在,在一个方法中,我创建了这个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对象时是否使用了正确的泛型


共 (2) 个答案

  1. # 1 楼答案

    不要使用extends/super,因为您将无法在映射中放置元素。它将给出一个编译错误

    Map<String, Number> uriVariables = = new HashMap<>();
    
  2. # 2 楼答案

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