ja jaaaa
ja jaaaa

Reputation: 115

NullPointerException in Map class

Long ago, I got the code from my ex colleague which worked for him but I can not make it work.

Using a debugger I concluded that my class has break point at this method:

((Map<String, List<byte[]>>)metaData).put(HEADERELEMENTS, headerOMElements); 

put method has declaration - String key, List <byte[]> value. I also tried with

((Map<String, List<byte]>>)metaData).put("HEADERELEMENTS",headerOMElements);

But it is the same situation. My printStackTrace returns NullPointerException. I did the logging of headerElements

number of headerOMElements (headerOMElements.size();)=1
headers are(before calling the method PUT) (headerOMElements.toString();): [[B@d000d]

How to conclude what is the problem and to resolve it? I am not high level Java expert so I really need help.

Upvotes: 0

Views: 195

Answers (2)

Stephen C
Stephen C

Reputation: 718836

Based on the limited information you have provided, and assuming that it is accurate, the only possible way1 that a NullPointerException can be thrown at that point is if metaData is null.

So ...

Modify your code to print out the value of metaData immediately before the statement where you believe that the NPE is being thrown; e.g.

System.err.println("metaData is " + metaData);

If the output shows that metaData is null, then the next step is to examine your code to figure out why it is null. The chances are you've not initialized it, or you've passed it in from somewhere else and it was null there too.

If the output shows that metaData is NOT null, then one of the facts / assumptions you've stated in your question has to be incorrect. For a further diagnosis, we would need:

  • the real code, copied and pasted (not typed in like you appear to have done ... based on the typos), and
  • the complete stack trace.

1 - For some kinds of Map you could also get an NPE if the key was null. However, that exception would be thrown within the put() method call. And besides, you say that you get the same problem when you use a literal String as a key. So that cannot be the explanation. The only other possible explanation is that there are multiple threads updating the map without synchronization. That might given an NPE (randomly), but the NPE would be in put or some other method of the Map instance.

Upvotes: 3

duffy356
duffy356

Reputation: 3718

If the data, which you want to put into the map is not null, before you put it in, your map might be null and you get a NullPointerException.

OR the Exception is thrown anywhere else.

Upvotes: 1

Related Questions