Search code examples
javahashmap

HashMap throws unwanted Null Pointer exception


From java docs of Map

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

But following code is throwing Null Pointer exception.

public class Main {
    public static void main(String args[]) throws Exception {
        boolean bool = false;
        Map<String, Boolean> map = new HashMap<>();
        boolean r = bool ? false : map.get("a");
    }
}

Can some one help me understand this behavior.


Solution

  • The issue here is not with the hashmap, but rather the auto-unboxing of the result to a primitive boolean.

    Use:

        Map<String, Boolean> map = new HashMap<>();
        Boolean r = map.get("a");
    

    Notice that r is a "big b" Boolean wrapper object, not a primitive boolean.

    As MadaManu points out, be aware that r can be null, which can be quite surprising to readers of your code. You might instead like to use:

        Map<String, Boolean> map = new HashMap<>();
        boolean r = map.getOrDefault("a", false);
    

    ... if you wish to treat the missing key as the same as false.