Programmer
Programmer

Reputation: 723

correct usage of generics while creating hashmap

I have a hashMap where key is String and value could be Integer or long . Now in a method I am creating this HashMap and passing into other method something like

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)
{
....
}

Just wanted to know whether i have used correct generics while creating hashMap object

Upvotes: 0

Views: 48

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

Map<String,? super Number> will return Object on get(). It is better to use Map<String, Number> then put() will accept Long and Integer and get() will return Number

Upvotes: 1

Abhijeet Kushe
Abhijeet Kushe

Reputation: 2597

Don't use extends/super as you will not be able to put elements in a Map.It will give a compilation error

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

Upvotes: 1

Related Questions