2013-05-28 65 views
0

我想將CD對象添加到CD的ArrayList的Band對象的ArrayList成員字段中。 band_index是從一個組合框中選擇的Band ArrayList的索引,並且我已經檢查過band_index是否爲所選擇的band指定了正確的索引。當我去調用當前Band的addCD方法時,我在這行代碼band.get(band_index).addCD(cd);上得到一個空指針異常。類內的Arraylists Java

主要類:

public void addCD() { 
    CD cd = new CD(t, y); 

    band.get(band_index).addCD(cd); //NULL pointer Exception on this line 
      updateCDs(); 
} 

//Method to print out all the CDs of a band 
public void updateCDs() { 
    String list = ""; 
    for(int i = 0; i < band.size(); i++) 
    { 
      //band_index is the index of the selected band in the combobox  
      if(i == band_index) { 
      for(int j = 0; j < band.get(i).getCDs().size(); j++) { 
       list += "Title: " + band.get(i).getCDs().get(j).getTitle(); 
       list += "Year: " + band.get(i).getCDs().get(j).getYear(); 
      } 
     } 
    } 
    System.out.println(list); 
} 

帶種類:

private ArrayList<CD> cds; 

public void addCD(CD cd) { 
    cds.add(cd); 
} 

CD類:

private String title; 
private int year; 

public CD(String t, int y) { 
    title = t; 
    year = y; 
} 

public getTitle() { return title; } 
public getYear() { return year; } 
+1

'band.get(band_index)'做了什麼?初始化'private ArrayList cds = new ArrayList <>();' – NINCOMPOOP

+0

你在初始化'band'的地方? –

+0

謝謝。我忘了它 – user1352609

回答

6

cds爲空。

試試這個:

private List<CD> cds = new ArrayList<CD>(); 

public void addCD(CD cd) { 
    cds.add(cd); 
} 

BTW。也許樂隊也是空的。沒有足夠的源代碼來確定這一點。

+0

這是一個簡單的錯誤。我忘了初始化CD ...謝謝 – user1352609