Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap get method null pointer exception

My code is similar to the following:

public class A {
        private HashMap<Character, Boolean> myMap;

        public A() {
            myMap = new HashMap<Character, Boolean>();
            String mychars = "asdfzxcvqwer";
            for (char c : mychars.toCharArray())
                myMap.put(c, true);
        }

        public void doo(String input) {
            StringBuilder output = new StringBuilder();
            for (char c : input.toCharArray()) {
                if (myMap.get(c))
                    output.append(c);
            }
        }
        //...
        //...
    }

Why am I getting a null pointer exception (NPE) at the line if (myMap.get(c))?


2 Answers

If c is not contained in myMap, it will return null, which can't be unboxed as a boolean.

Try :

Boolean b = myMap.get(c);
if(b != null && b){
...
like image 70
xlecoustillier Avatar answered Sep 05 '25 04:09

xlecoustillier


If myMap doesn't contain a key that matches c, then myMap.get(c) will return null. In that case, when the JVM unboxes what it expects to be a java.lang.Boolean object into a boolean primitive to execute the condition, it founds a null object and therefore throws a java.lang.NullPointerException.

The following block is equivalent to what you have in your example and should make it easier to understand why you would have a NullPointerException:

if (((Boolean) myMap.get(c)).booleanValue()) 

I would re-write your original condition as:

if ( myMap.containsKey(c) )

I hope this helps.

like image 44
Nuno Guerreiro Avatar answered Sep 05 '25 05:09

Nuno Guerreiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!