我需要在Java中初始化地图列表,但是我尝试将其初始化为null的所有方式

时间:2019-05-15 06:23:24

标签: java

因此,我尝试初始化地图列表,但是以每种方式初始化它时,它的初始值为null。

因此,我尝试使用Google搜索和堆栈溢出,并且有一些类似的帖子,但没有明确的内容。只是好奇我如何初始化它,所以它不为null,因此我可以稍后在代码中添加它。

List<Map<String, Response>> listOfResponses = new ArrayList<Map<String, Response>>();

然后我要如何添加到列表:

HashMap<String, Response> thisResponse = new HashMap<>();
    int i = 1;
    for (Question q : questions)
    {
        if( q == null)
        {
            return;
        }
        else {
            q.DisplayQuestion();
            mo.displayString("Please enter your response for the previous question: ");
            Response r = Response.CreateResponse(mi.getNextString());
            q.setResponse(r);
            thisResponse.put(Integer.toString(i), r);
            //q.setResponse(Response.CreateResponse(mi.getNextString()));
            i++;
        }
    }
    listOfResponses.add(thisResponse);
    Save(this);

错误消息是一个空指针,因为列表初始化为空,这意味着它不能被添加到其中。

真实错误消息堆栈跟踪:

in thread "main" java.lang.NullPointerException
    at com.company.Survey.TakeSurvey(Survey.java:304)
    at com.company.Menu.SurveyMenu(Menu.java:129)
    at com.company.Menu.SurveyMenu(Menu.java:78)
    at com.company.Menu.StartMenu(Menu.java:24)
    at com.company.Main.main(Main.java:21)

1 个答案:

答案 0 :(得分:1)

您的问题是您正在重用 same 映射,并且仅将单个映射添加到响应中,并且仅当没有空问题时才会中止该方法,而无需使用/保存{{1 }}。

您的代码应类似于:

thisResponse