空检查映射得到空指针异常 [英] Null check in map gets null pointer exception

查看:116
本文介绍了空检查映射得到空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java HashMap 。使用 map.get(A)从映射中获取键的值导致 NullPointerException 。然后,我使用 if(map.get(A))来避免抛出 NullPointerException ,但它会得到



我做错了什么?

解决方案

I回答我自己的问题。我曾用来检查

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

而不是

<$如果(map.get(A)!= null)
map.get(A)

p $ p>

它可以帮助我避免空指针异常


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?

解决方案

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

这篇关于空检查映射得到空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆