ArrayList.add()方法导致NullPointerException

Oca*_*shu 4 java arraylist nullpointerexception

LongInteger类在运行时导致以下错误:

Exception in thread "main" java.lang.NullPointerException
at LongInteger.breakString(LongInteger.java:38)
at LongInteger.<init>(LongInteger.java:17)
at LongInteger.main(LongInteger.java:149)
Run Code Online (Sandbox Code Playgroud)

以下是一些相关的课程摘录:

public class LongInteger extends Object {
private ArrayList<String> storedStrings;          


  // Constructor
 public LongInteger(String s) {
    this.setInputString(s);
    this.breakString(this.inputString);       //Exception @ line 17
}

 /**
  * the purpose of this method is to break the input string into an 
  * ArrayList<String> where each String has a length of 9 or less.
  */
 private void breakString(String s){         
    if(s.length()>9){
        storedStrings.add(0,s.substring(s.length()-9,s.length()));
        this.breakString(s.substring(0,s.length()-9));
    } else {
        this.storedStrings.add(0,s);        //Exception @ line 38
    }
 }


public static void main(String[] args) {
    LongInteger a = new LongInteger("12345");   //Exception @ line 149
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道是什么导致了这个NullPointerException.有人有建议吗?

Kir*_*oll 17

你永远不会实例化storedStrings.尝试改变:

private ArrayList<String> storedStrings;
Run Code Online (Sandbox Code Playgroud)

至:

private ArrayList<String> storedStrings = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

如果你有这条线:

this.storedStrings.add(0,s);
Run Code Online (Sandbox Code Playgroud)

正在调用该方法add的一个实例ArrayList<String>存储在this.storedStrings.该new运营商是如何得到的东西新的实例.