1

I am trying to add objects to an ArrayList from another file but I am getting a java.lang.NullPointerException even though I have initialized the ArrayList. Here is an example of the code with the structure that I am talking about.

//ObjectOne.java

import java.util.ArrayList;

public class ObjectOne {   

    public InnerClass inner;

   class InnerClass {

       ArrayList<String> list = new ArrayList<String>();

       public void addString(String str) {
           list.add(str);
       }

   }

   public void addStr(String str) {
       inner.list.add(str);
   }


}

Here is the second file:

//ObjectTwo.java
public class ObjectTwo {

    public static void main(String args[]) {
        ObjectOne obj = new ObjectOne();
        obj.addStr("Test string added");
    }

}

I have initialized the ArrayList in InnerClassbut when I try to add an item in another java file I get a NullPointerException. The reason I have this file structure is because I am working with GSON. Why is the ArrayList list acting as if it was never initialized? My goal is to be able to add objects to the list from a different java file.

Rowen McDaniel
  • 169
  • 1
  • 2
  • 11

1 Answers1

1

You did not create an instance of the inner class in the parent class, only created a reference for it.

public InnerClass inner = new InnerClass(); // add the new here
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504