【问题标题】:Arraylists within a class JavaJava 类中的数组列表
【发布时间】: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&lt;CD&gt; cds = new ArrayList&lt;&gt;();
  • 你在哪里初始化band
  • 谢谢。我忘了它
  • 在 updateCDs() 中使用 StringBuilder 并查看它的代码我不明白您为什么不将其称为 printCDs() 之类的?
  • 一般的做法是:启动调试器,首先找出哪个子表达式是null

标签: java arrays oop arraylist


【解决方案1】:

您的cds 为空。

试试这个:

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

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

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

【讨论】:

  • 这是一个简单的错误。我忘了初始化 cds...谢谢
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 2011-12-23
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
相关资源
最近更新 更多