【发布时间】:2013-05-23 08:28:02
【问题描述】:
我正在尝试将 CD 对象添加到 CD ArrayList 的 Band Object 的 ArrayList 成员字段中。 band_index 是从组合框中选择 Band ArrayList 时的索引,并且我检查了 band_index 确实分配了所选波段的正确索引。当我去调用当前乐队的 addCD 方法时,我在这行代码 band.get(band_index).addCD(cd); 上得到一个空指针异常。
主类:
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; }
【问题讨论】:
-
band.get(band_index)是做什么的?初始化private ArrayList<CD> cds = new ArrayList<>(); -
你在哪里初始化
band? -
谢谢。我忘了它
-
在 updateCDs() 中使用 StringBuilder 并查看它的代码我不明白您为什么不将其称为 printCDs() 之类的?
-
一般的做法是:启动调试器,首先找出哪个子表达式是
null。