Unboxing of 'map.get(key)' may produce 'NullPointerException'

Viewed 3439

This code

public static int getValue(int key) {
    return map.get(key);
}

private static Map<Integer, Integer> map;
static {
    map = new HashMap<>();
    map.put(1, 1);
    map.put(2, 2);
}

produces a Lint warning

Unboxing of 'map.get(key)' may produce 'NullPointerException'

This warning can be fixed by checking for null:

public static int getValue(int key) {
    Integer n = map.get(key);
    return n != null ? n : -42;
}

Is there a better way?

1 Answers
Related