我正在尝试将 CD 对象添加到 CD ArrayList 的 Band Object 的 ArrayList 成员字段中。band_index 是从组合框中选择 Band ArrayList 时的索引,并且我检查了 band_index 确实分配了所选波段的正确索引。band.get(band_index).addCD(cd);
当我去调用当前乐队的 addCD 方法时,我在这行代码上得到一个空指针异常。
主类:
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; }