Java HashMap get method null pointer exception

2020-02-26 04:46发布

I have code similar to the following :-

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 doo(String input)
  {
    StringBuilder output = new StringBuilder();
    for ( char c : input.toCharArray() )
    {
      if ( myMap.get(c) )
         output.append(c);
    }
  }
  ...
  ...
}

I get a null pointer exception at the line if ( myMap.get(c) ) -- What am I doing wrong?

7条回答
虎瘦雄心在
2楼-- · 2020-02-26 05:18

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.

查看更多
登录 后发表回答