I have two cards in my class (I'm new to generics)
private Map<Integer, Integer> aMap = new ConcurrentHashMap<Integer, Integer>(); private Map<Integer, Short> bMap = new HashMap<Integer, Short>();
If there is no key on the card, I want to get a null value. So I made this wrapper method to minimize the typing of 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
In the second case, it gives me:
ClassCastException: java.lang.Integer cannot be cast to java.lang.Short
Therefore, probably, I will need to do something like : new Number(0) , but Number is abstract.
How to fix it?
EDIT:
My idea is to do arithmetic operations without additional ifs:
Integer a = getValue(aMap, 15); a = a + 10;
source share