将字符串对象添加到arraylist时出现空指针异常

时间:2013-04-26 15:50:15

标签: java arraylist nullpointerexception

不能解决这个问题。尝试将String对象添加到ArrayList时发生空指针异常。麻烦的是,我相信我已经正确初始化了'temp'ArrayList。请帮忙。

void initialConbinations(String[] headers) {
    //Dataset is SN,FN,RN,PN
    //Map the headers to the appropriate portions
    String[] newHeaders = {"SN,high", "SN,medium", "SN,low", "FN,high", "FN,medium", "FN,low", "RN,high", "RN,medium", "RN,low"};
    List<List> assRuleHeaders = new ArrayList<List>();
    ArrayList<String> temp = new ArrayList<String>();

    //Use bitwise shifting to do the rest
    int k = 0, l = 0;
    for (int i = 1; i < 511; i++) {
        for (int j = 0; j < 9; j++) {
            l = i;
            k = (l >> j) & 0x00000001;
            if (k == 1) {
                System.out.println(k + " , " + i + " , " + j);
                System.out.println(newHeaders[j]);
                temp.add(newHeaders[j]);    //Getting a Null Pointer Exception here
            }
        }
        assRuleHeaders.add(temp);
        temp = null;
    }

    for (int i = 0; i < assRuleHeaders.size(); i++) {
        this.printArray(assRuleHeaders.get(i));
    }
}

2 个答案:

答案 0 :(得分:12)

错误在于

temp = null;

您不会再次重新初始化temp

如果你移动线

ArrayList<String> temp = new ArrayList<String>();
两个for循环之间的

都应该没问题。

答案 1 :(得分:3)

i循环的最后一步,您将temp设置为null,而不是使用new ArrayList<String>();将其设置为新数组。这将导致temp.add(newHeaders[j]);通过空指针异常。

变化

temp = null;

temp = new ArrayList<String>();