Sara
Sara

Reputation: 335

Null check in map gets null pointer exception

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?

Upvotes: 4

Views: 16164

Answers (4)

Rakesh KR
Rakesh KR

Reputation: 6527

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
   }
} 

Upvotes: 0

Sara
Sara

Reputation: 335

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

Upvotes: 5

Yair Nevet
Yair Nevet

Reputation: 13003

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*/}

Upvotes: 2

Code-Apprentice
Code-Apprentice

Reputation: 83527

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.

Upvotes: 1

Related Questions