ArrayList.add()方法导致NullPointerException

时间:2012-02-16 01:31:02

标签: 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)

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

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
    }
}

我对导致此NullPointerException的原因感到茫然。有人有建议吗?

2 个答案:

答案 0 :(得分:17)

您永远不会实例化storedStrings。尝试更改:

private ArrayList<String> storedStrings;

要:

private ArrayList<String> storedStrings = new ArrayList<String>();

当你有这条线时:

this.storedStrings.add(0,s);

它在add中存储的ArrayList<String>实例上调用方法this.storedStringsnew运算符是您获取新事物的方式。

答案 1 :(得分:3)

您需要在使用之前创建storedStrings变量。

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