在向ArrayList添加字符串对象时出现空指针异常。

3

无法解决这个问题。尝试将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));
    }
}

那里有很多多余的代码。能不能稍微整理一下,让它更容易看清楚?还有,请把打印流粘贴一下好吗? - user1131435
不好意思。我是个新手,下次会更小心。 - undefined
2个回答

12

错误出在这行代码上

temp = null;

您没有再次重新初始化temp

如果您将此行移动

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

在这两个for循环之间,一切都应该是正常的。


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

更改:

temp = null;

to

temp = new ArrayList<String>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接