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 InnerClass
but 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.