2013-04-26 43 views
2

無法繞過此操作。嘗試將String對象添加到ArrayList時發生空指針異常。麻煩的是,我相信我已經正確地初始化了'temp'ArrayList。請幫忙。向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)); 
    } 
} 
+0

那裏面有很多多餘的代碼。清理它有點讓它更容易看到?另外,請記住粘貼打印流? – Zyerah 2013-04-26 15:51:57

+0

對不起。這裏的新手,下次會更加小心。 – 2013-04-26 15:57:39

回答

12

錯誤是你是不是又重新初始化temp

temp = null; 

如果招行

ArrayList<String> temp = new ArrayList<String>(); 
兩者之間

for循環都應該罰款。

+0

謝謝,非常感謝。這有幫助。 – 2013-04-26 15:56:04

+1

太好了。很高興我能幫上忙。不要忘記標記爲答案:) – 2013-04-26 15:56:22

3

在最後一步i循環中,您將temp設置爲null,而不是使用new ArrayList<String>();將其設置爲新的數組。這將導致temp.add(newHeaders[j]);通過空指針異常。

變化

temp = null; 

temp = new ArrayList<String>();