I have two maps in my class (I am new to generics)
private Map<Integer, Integer> aMap = new ConcurrentHashMap<Integer, Integer>();
private Map<Integer, Short> bMap = new HashMap<Integer, Short>();
If key does not exist in map I want to get a zero value. So I have made this wrapper method to minimize typing containsKey(key)
@SuppressWarnings("unchecked")
private <T extends Number> T getValue (Map<Integer, T> map, Integer key) {
return (T) ((map.containsKey(key)) ? map.get(key) : 0);
}
I call it like
Integer a = getValue(aMap, 15); //okay in any case
Short b = getValue(bMap, 15); //15 key does not exist
For second case it gives me:
ClassCastException: java.lang.Integer cannot be cast to java.lang.Short
So probably I would need to do something like : new Number(0)
, but Number is abstract.
How can I fix it?
EDIT:
My idea is to do arithmetic operations without additional ifs:
Integer a = getValue(aMap, 15);
a = a + 10;
One way is to supply the default value as an argument to your function:
private <T extends Number> T getValue (Map<Integer, T> map, Integer key, T dflt) {
return (T) ((map.containsKey(key)) ? map.get(key) : dflt);
}
public static void main(String[] args) {
Integer a = getValue(aMap, 15, 0); //okay in any case
Short b = getValue(bMap, 15, (short)0); //15 key does not exist
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With