4

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
  • 1
    Please show a complete code example. In particular, you need to include declarations for any relevant variables. Also be sure that the provided code accurately illustrates the issue you are asking about and doesn't introduce unrelated errors. Commented Oct 25, 2014 at 6:09

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

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 Comments

Note that the if statement will only compile if the OP has Map<String, Boolean> map.
if(map.get("A")) will cause a compiler error. This isn't C++ or Python.
This will not work if we doesn't put map.put("A", "someValue");and try if(map.get("A") != null)
1

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.

Comments

0

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

1 Comment

What if the the map is null in the First case, map.containsKey() will throw a null pointer!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.