Null check in map gets null pointer exception

时光怂恿深爱的人放手 提交于 2019-12-11 06:53:18

问题


I am trying to use a Java HashMap. Using map.get("A") to get a value for a key from the map resulted in a NullPointerException. Then I used if(map.get("A")) to avoid a NullPointerException being thrown, but it gets thrown anyway.

What am I doing wrong?


回答1:


I have answering my own question. I have used to check

         if(map.containsKey("A"))
                 String b =  map.get("A")

rather than

    if(map.get("A") != null)
            map.get("A")

It will help me to avoid null pointer exception




回答2:


Well, you probably didn't instantiate the map object itself.

Try this before accessing the map:

Map map = new HashMap();

And later:

map.put("A", "someValue");
if(map.get("A") != null){/*your code here*/}



回答3:


There are two possible problems:

  1. map itself is null because you never initialized it.

  2. map is declared as Map<String, Boolean> map. If this is the case, then your if statement doesn't do what you think it does. It actually gets the Boolean object from the map and tries to unbox it to a primitive bool. If there is no value with the key "A", then you will get a NullPointerException. The way to fix this is to change your if statement:

    Boolean b = map.get("A");
    if (b != null && b)
        ...
    

    Note that you have to explicitly compare with null.




回答4:


First of all check whether the map is null or not by

map != null

Then check map contains that key by,

map.containsKey("A")

Totally you can check as follows,

if(map!=null && map.containsKey("A")){
   if(map.get("A") != null){
       System.out.println(map.get("A"));
       \\ value corresponding to key A
   }
} 


来源:https://stackoverflow.com/questions/26559768/null-check-in-map-gets-null-pointer-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!