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

2

7

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?

Adley answered 4/6, 2020 at 10:21 Comment(3)
Let getValue return an Integer instead. But then again, you'd probably get another warning when you're trying to use that return value somewhere elseIndolence
This works - and no new warning appears somewhere else.Adley
This works probably because each method has NonNull annotation by default. When I add Nullable annotation to getValue, the warning appears in the calling method.Adley
S
6

As of Java 8, you may use getOrDefault, as per the docs: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-

Shipmate answered 4/6, 2020 at 10:37 Comment(1)
This will not solve the issue. Even when giving the default value, casting to int will still show the warning.Oeillade
M
0

I know this is late, but as I said here: Unboxing may produce Null Pointer Exception after checking if key exists in Map, you have to perform a null check because values explicitly mapped to null are retrieved as null.

Mistral answered 29/3 at 0:44 Comment(2)
Maybe you can edit your answer and post code that demonstrates how to perform this null check - since your other answer does not contain such code either.Strontianite
No, the question already has the correct null check. They were asking whether or not there's a better way.Mistral

© 2022 - 2024 — McMap. All rights reserved.