在不同的类中向ArrayList添加项

时间:2014-04-02 14:44:50

标签: java arraylist

对于作业,我必须创建一个Java应用程序,其中一个我遇到问题的函数是添加到ArrayListArrayList与方法不同,我得到一个nullpointer(当我将它设置为静态时不会发生)。

这是我要添加的代码:

if (e.getSource() == voegToe) {
   if (naam.equals("") || straat.equals("") || huisnummer.equals("")
                || postcode.equals("") || plaats.equals("")
                || telefoonnummer.equals("") || email.equals("")) {

            allesoke = false;
            foutmelding += "\n";
  }

  if (allesoke == true) {
      Klant newKlant = new Klant (naam, postcode, huisnummer);
      System.out.println("HOI");
      klantenBindingRef.alleKlanten.add(newKlant);
      System.out.println(klantenBindingRef.alleKlanten);
  } else {
      JOptionPane.showMessageDialog(null, foutmelding, "Foutmelding",
            JOptionPane.INFORMATION_MESSAGE, null);
  }

这是使用ArrayList

的类代码的一部分
public class Klantenbinding {
private String naam;
protected List<Klant> alleKlanten = new ArrayList<Klant> ();

// klanten
public void voegKlantToe(Klant nweKlant) {

    if (!heeftKlant(nweKlant.getNaam())) {
        alleKlanten.add(nweKlant);
    }
}
    public boolean heeftKlant(String naam) {
    boolean b = false;
    for (Klant k : alleKlanten) {
        if (k.getNaam() == naam) {
            b = true;
        }
    }
    return b;
}

nullpointer来自以下行:

klantenBindingRef.alleKlanten.add(newKlant);

public class KlantToevoegen extends JFrame implements ActionListener {
/**
 * 
 */
JFrame frame;
private static final long serialVersionUID = 1L;
private JButton voegToe, terug;
private JPanel contentPane;
private JTextField nmTf, strTf, hnrTf, pcTf, plTf, telnrTf, emailTf;
private JLabel lblAanhef, lblNaam, lblStraat, lblNieuweKlantToevoegen,
        lblHuisnr, lblPostcode, lblPlaats, lblTelnr, lblEmail;
private JComboBox aanhefBox;
private Klantenbinding klantenBindingRef;
private AutoToevoegenFrame autoToevoegenFrameRef;
private JSeparator separator;
private JSeparator separator_1;

/**
 * Launch the application.
 */

4 个答案:

答案 0 :(得分:0)

您是否尝试导入包含ArrayList的类? (暂无评论)

答案 1 :(得分:0)

我敢打赌你的变量klantenBindingRef永远不会被初始化。

答案 2 :(得分:0)

尝试以这种方式比较您的字符串以避免NPE

if ("".equals(naam) || "".equals(straat) || ...) {
    allesoke = false;
    foutmelding += "\n";
}

然后验证klantenBindingRef在访问其变量之前是否已实例化

//klantenBindingRef is null
klantenBindingRef = new Klantenbinding();
klantenBindingRef.alleKlanten
...

答案 3 :(得分:0)

在使用klantenBindingRef

之前初始化变量klantenBindingRef = new Klantenbinding();
if( klantenBindingRef == null ) 
    klantenBindingRef = new Klantenbinding();
klantenBindingRef.alleKlanten.add(newKlant);