0

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

2 Answers 2

1

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<>();
Sign up to request clarification or add additional context in comments.

2 Comments

I have used super not extends
Yep just saw that .Corrected my answer.Have a look a this link for getting more info about adding elements with lower bounded wildcards docs.oracle.com/javase/tutorial/java/generics/lowerBounded.html
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.