2012-11-01 32 views
-1

我得到一個空指針異常,並在下面的代碼中嘗試將由「newColumn」引用的對象添加到由Java中的「this.neighborColumns」引用的ArrayList 。我在這裏先向您的幫助表示感謝。將對象添加到數組列表時出現空指針異常

for (int column = xInitial; column < xFinal; ++column) 
    { 
     for (int row = yInitial; row < yFinal; ++row) 
     { 
      // TODO: To make inhibition a circle around input column, change 
      // to remove conners of this rectangle inhibition 
      Column newColumn = this.region.getColumn(column, row); 
      if (newColumn != null) 
      { 
       this.neighborColumns.add(newColumn); 
      } 
     } 
    } 
+0

你在哪裏實例化'neighborColumn'對象?在構造函數或其他地方? – Grambot

+1

發佈你的stacktrace,但在猜測neighbourColumns爲null。 – Goibniu

+0

請發佈您的堆棧跟蹤代碼的相關部分,例如'this.neighborColumns'如何表現。你嘗試過調試器嗎? – home

回答

0

您的代碼沒有顯示你怎麼有之前初始化它定義this.neighborColumns名單,但根據您的問題標題,我猜this.neighborColumns指向空;

指定neighborColums在執行任何操作之前列出實現對象。例如:

neighborColumns = new ArrayList<type>(); 
1

你可能還沒有初始化你的數組列表neighborColumns

你打電話之前加上它

List<Type> neighborColumns = new ArrayList<>(); 

它能夠更好地檢查數組列表是空你加東西進去

if (newColumn != null && neighborColumns !=NULL) 
      { 
       this.neighborColumns.add(newColumn); 
      }