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");
}
}
当我尝试将字符串传递给loadStateNames时。我得到一个空指针异常。无法找出导致此错误的原因。
Exception in thread "main" java.lang.NullPointerException
at com.assignment.Interview.loadStateNames(Interview.java:41)
at com.assignment.Interview.main(Interview.java:57)
最佳答案
您没有初始化它们。您应该在构造函数中执行此操作:
public Inteview() {
stateNames = new HashMap<>();
}
另外,我怀疑您是否想对
null
和stateCounts
提供inputList
引用。它们也应该在构造函数中初始化:public Inteview() {
stateNames = new HashMap<>();
stateCounts = new HasMap<>();
inputList = new ArrayList<>();
}