user2154424
user2154424

Reputation: 31

Null pointer exception when trying assign values to hashmap

package com.assignment;

import java.util.ArrayList;
import java.util.HashMap;



public class Interview {

private HashMap<String,Integer> stateCounts = null;
private HashMap<String,String> stateNames;
private ArrayList<InputData> inputList = null;


public void loadStateNames(String stateKey,String stateName)
{
    stateNames.put(stateKey, stateName);
}


public static void main(String Args[])
{
    Interview interview = new Interview();
    interview.loadStateNames("NY", "New York");
}
}

When I try to pass to strings to loadStateNames. I get a null pointer exception. Can't figure out whats causing this error.

Exception in thread "main" java.lang.NullPointerException
at com.assignment.Interview.loadStateNames(Interview.java:41)
at com.assignment.Interview.main(Interview.java:57)

Upvotes: 0

Views: 1947

Answers (5)

Ashot Karakhanyan
Ashot Karakhanyan

Reputation: 2830

You should create an instance:

private HashMap<String,String> stateNames = new HashMap<String, String>();

And for others too. BTW use interface in left side for polymorphism and in Java 7+ you don't need provide types in right side:

 private Map<String,String> stateNames = new HashMap<>();

Upvotes: 2

peter.petrov
peter.petrov

Reputation: 39457

When you declare a class variable like this:

private HashMap<String,String> stateNames;

or like this:

private HashMap<String,String> stateNames = null;

it is initialized with null.

You cannot add keys/values to it when it is null.

Either initialize it in a constructor or at declaration time.

private HashMap<String,String> stateNames = new HashMap<String,String>()

Upvotes: 2

Christian Tapia
Christian Tapia

Reputation: 34146

You are not initializing them. You should do this in the constructor:

public Inteview() {
    stateNames = new HashMap<>();
}

Also, I doubt you want to give a null reference to stateCounts and inputList. They should also be initialized in the constructor:

public Inteview() {
    stateNames = new HashMap<>();
    stateCounts = new HasMap<>();
    inputList = new ArrayList<>();
}

Upvotes: 2

Nir Alfasi
Nir Alfasi

Reputation: 53535

You forgot to initialize your HashMap, change:

private HashMap<String,String> stateNames;

to:

private HashMap<String,String> stateNames = new HashMap<String,String>();

Upvotes: 3

Kick
Kick

Reputation: 4923

You have not initialised the Map ,change it to ::

private HashMap<String,String> stateNames = new HashMap<String,String>();

Upvotes: 3

Related Questions