Question

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;
Was it helpful?

Solution

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
}

OTHER TIPS

Well, you can't do much about that without also providing T in a way that code can look at.

The simplest approach at that point would probably be to keep a map of 0 values:

private static Map<Class<?>, Number> ZERO_VALUES = createZeroValues();

private static Map<Class<?>, Number> createZeroValues() {
    Map<Class<?>, Number> ret = new HashMap<Class<?>, Number>();
    ret.put(Integer.class, (int) 0);
    ret.put(Short.class, (short) 0);
    ret.put(Long.class, (long) 0);
    // etc
}

Then:

private <T extends Number> T getValue (Map<Integer, T> map, Integer key, Class<T> clazz) {
    return clazz.cast(map.containsKey(key) ? map.get(key) : ZERO_VALUES.get(clazz));
}

Then you'd unfortunately have to call it as:

Short b = getValue(bMap, 15, Short.class);

Basically this is a limitation of Java generics :(

In situations like this, I just override the get() method:

 private Map<Integer, Short> bMap = new HashMap<Integer, Short>() {
     @Override
     public Short get(Object key) {
         return containsKey(key) ? super.get(key) : new Short(0);
     }
 };

Then you can just use it anywhere and it will behave as you specified.

Cast 0 to short explicitly as it will be int by default. And then convert to Short wrapper. In java u cannot directly convert from primitive to a Wrapper of a different type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top