Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException while using put method of HashMap

The following code is giving me a NullPointerException. The problem is on the following line:

...  dataMap.put(nextLine[0], nextLine[6]); 

What is strange is that I have run this code without the above line and the call to nextLine[0] and nextLine[6] work exactly as expected - that is they give me back elements of a csv file. I declare and initialise the HashMap with the code

HashMap<String, String> dataMap = null; 

earlier in the method

  String[] nextLine;   int counter=0;   while (counter<40) {     counter++;      System.out.println(counter);     nextLine = reader.readNext();      // nextLine[] is an array of values from the line     System.out.println(nextLine[0] + " - " + nextLine[6] +" - " + "etc...");     dataMap.put(nextLine[0], nextLine[6]);   }   return dataMap; } 
like image 303
Ankur Avatar asked Apr 09 '09 16:04

Ankur


People also ask

How do I fix NullPointerException?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

How do I avoid NullPointerException?

How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.

Can we insert null in HashMap?

HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.

Which of the following options can throw a NullPointerException?

Some of the most common scenarios for a NullPointerException are: Calling methods on a null object. Accessing a null object's properties. Accessing an index element (like in an array) of a null object.


2 Answers

HashMap<String, String> dataMap = new HashMap<String,String>(); 

Your dataMap variable isn't initialized at this point. You should be getting a compiler warning about that.

like image 169
Codingscape Avatar answered Oct 05 '22 22:10

Codingscape


Where is datamap initialised ? It's always null.

To clarify, you declare the variable and set it to null. But you need to instantiate a new Map, whether it's a HashMap or similar.

e.g.

datamap = new HashMap(); 

(leaving aside generics etc.)

like image 33
Brian Agnew Avatar answered Oct 05 '22 22:10

Brian Agnew