0

So I'm trying to initialize a List of Maps, but every way I initialize it, it inits to null.

So I've tried googling and stack overflowing this, and there are some similar posts, but nothing explicitly like this. Just curious how I can init this so it isn't null, so I can add to it later in the code.

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

Then how I'm trying to add to list:

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

Error message is a nullpointer, because the list is initing to null, meaning it can't be added to.

Real Error message stack trace:

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)
  • 3
    Please show how you are attempting to add elements to that list. – Eran May 15 '19 at 06:25
  • 1
    How are you trying to use `listOfResponses` after you initialize it? This seems fine to me, you could just do it like `List> listOfResponses = new ArrayList<>();`, though. – lealceldeiro May 15 '19 at 06:26
  • 1
    If you've executed the code mentioned in your post, the List should not init to null, it should be an empty list. – shriakhilc May 15 '19 at 06:26
  • Where do you add anything to the list? To get the null error you mention, you need to add null to the list, because else you get an array index out of bounds exception – Ferrybig May 15 '19 at 06:26
  • Please add the code that "doesn't work" to your question. See [MCVE](https://stackoverflow.com/help/mcve). – Bohemian May 15 '19 at 06:27
  • The correct way to declare such a list and right away create an empty instance boils down to: `List> listOfResponses = new ArrayList<>`. It doesnt matter that your list is supposed to hold maps or whatnot. You just create an empty list, which is NOT null, but of course NOT containing any map objects initially! – GhostCat May 15 '19 at 06:28
  • By any chance are you doing something like `listOfResponses.get(0).put("foo", someResponse);`? – Bohemian May 15 '19 at 06:29
  • There's no way that the list inits to null, you're just not calling the init before trying to add something to the list. – Breina May 15 '19 at 06:31
  • _Error message is a nullpointer_ Do you get this error message when you run the code you posted? If so, then please post the entire stack trace you are getting. – Abra May 15 '19 at 06:31
  • https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it+ – GhostCat May 15 '19 at 06:34
  • And unrelated: A) you still didnt provide a full [mcve] ... show us that TakeSurvey() method, and tell us which line no 304 is ... B) learn about java naming conventions. Method names go camelCase() in java. – GhostCat May 15 '19 at 06:35
  • The stacktrace is not useful unless you tell us which line of your code is line 304 (and even then may not be useful). Also, I suspect now that the code you have listed is not the code that you are running, because as it stands the code will not throw a NPE for the reasons you believe. Do you recompile your code before executing it? – Bohemian May 15 '19 at 17:13

1 Answers1

1

Your problem is you are reusing the same map, and only adding that single map to the responses, and only if there are no null questions, which aborts the method without using/saving thisResponse at all.

Your code should look more like:

for (Question q : questions) {
    if (q == null) {
        continue;  // ignore nulls
    }
    HashMap<String, Response> thisResponse = new HashMap<>();
    listOfResponses.add(thisResponse);
    // populate thisResponse
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • So, in other words, this is a DUP of https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it+ ... and should imho be closed as such. – GhostCat May 15 '19 at 06:36
  • @Bohemian a lot's of variable are unknown in OP's code snippet like `mi`, `q` and `mo`. So how are you analyzing them ? May be one of them is `null`. – Sudhir Ojha May 15 '19 at 06:36
  • Right, this is totally a misunderstanding of nullpointers and not a question on how to initialize and add to a list of maps...because not understanding why int x; is null and not understanding why a list of maps is null when initialized as a hash map are the same :). – user11502261 May 15 '19 at 06:40
  • Mo and Mi are simply MyOutput and MyInput which are just custom classes to avoid System.out.println(string) over and over again since it is a software design project in which the parameters of the "user" are always changing. So MyO and MyI may need to implement image options in the future. – user11502261 May 15 '19 at 06:42
  • @user11502261 Please stop. You are just adding to the confusion. Read that link about "NPE and how to fix it". Take your time. It might take *hours* of study for you to get through all of this. Then, if you still cant make progress with your code, show a **real** [mcve]. As written before: what you put up so far is not sufficient to give you a reasonable answer (beyond guessing: this or that is null). – GhostCat May 15 '19 at 06:56