Ankur
Ankur

Reputation: 51110

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

Upvotes: 27

Views: 55407

Answers (6)

SaadurRehman
SaadurRehman

Reputation: 660

My case was different as Usually, hashmaps throw the null pointer exception when trying to read a key that is not there e.g I have a

HashMap<String, Integer> map = new HashMap<String, Integer>();

Which is empty or have keys except "someKey", So when I try to

map.get("someKey") == 0;

Now this will produce a nullPointerExeption due to matching a null with some integer.

What should I do instead?

Ans: I should instead check for null like

map.get("someKey") != null;

Now the runtime error Nullpointer would not raise!

Upvotes: 0

Codingscape
Codingscape

Reputation: 579

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.

Upvotes: 47

Michael Borgwardt
Michael Borgwardt

Reputation: 346457

Um, what exactly do you expect when you do this?

HashMap<String, String> dataMap = null;
...
dataMap.put(...)

Upvotes: -1

jcopenha
jcopenha

Reputation: 3975

Well, there are three objects accessed on that line. If nextLine[0] and nextLine[6] aren't null, because the println call above worked, then that leaves dataMap. Did you do dataMap = new HashMap(); somwehere?

Upvotes: 1

Sheldon
Sheldon

Reputation: 391

dataMap is declared but not initialized. It can be initialized with

datamap = new HashMap();

Upvotes: 3

Brian Agnew
Brian Agnew

Reputation: 272367

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.)

Upvotes: 5

Related Questions