问题
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:
mapitself isnullbecause you never initialized it.mapis declared asMap<String, Boolean> map. If this is the case, then yourifstatement doesn't do what you think it does. It actually gets theBooleanobject from the map and tries to unbox it to a primitivebool. If there is no value with the key"A", then you will get aNullPointerException. The way to fix this is to change yourifstatement: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