Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic 0 cannot be cast to java.lang.Short

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;
like image 303
Nikolay Kuznetsov Avatar asked Dec 21 '22 08:12

Nikolay Kuznetsov


1 Answers

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
}
like image 187
NPE Avatar answered Jan 09 '23 19:01

NPE