类Java中的Arraylists

use*_*609 0 java arrays oop arraylist

我试图将CD对象添加到CD的ArrayList的Band Object的ArrayList成员字段中.band_index是Band ArrayList的索引,当它从组合框中选择时,我已经检查了band_index确实分配了所选波段的正确索引.band.get(band_index).addCD(cd);当我去调用当前Band的addCD方法时,我在这行代码上得到一个Null Pointer Exception .

主要课程:

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);
}
Run Code Online (Sandbox Code Playgroud)

乐队类:

private ArrayList<CD> cds;

public void addCD(CD cd) {
    cds.add(cd);
}
Run Code Online (Sandbox Code Playgroud)

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; }
Run Code Online (Sandbox Code Playgroud)

Ste*_*ike 6

你的cds是空的.

试试这个:

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

public void addCD(CD cd) {
    cds.add(cd);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句.也许乐队也是空的.没有足够的源代码来确定这一点.