我有一个函数“ getStudent()”,该函数返回字符串的ArrayList,当我在另一个类中调用此函数时,出现NullPointerException,我认为我已经正确初始化了我的List。

这是两个函数,我得到的NullPointerException行以粗体显示。

 public ArrayList<String> getStudents(){

try
{
    System.out.println("gets here ");

    Statement newStat = this.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet res = newStat.executeQuery("SELECT FirstName FROM Students");

            String data = "";
    while (res.next()){

    studentList.add(res.getString("FirstName"));
    }

}
catch(SQLException e){
    System.err.println("SQLException: " + e.getMessage());
}
 return studentList;
}


调用“ getStudents()”的函数

  public class CancelListener implements ActionListener{
    private  Main_Menu menu;
    private ArrayList<String> arrayList = new ArrayList<String>();;
    Iterator iterator = arrayList.iterator();


      public CancelListener(Main_Menu menu) {
      this.menu = menu;
    }

  @Override
    public void actionPerformed(ActionEvent ae) {
    if(ae.getActionCommand().equalsIgnoreCase("Cancel")){

    **arrayList = StudentModel.getStudents();**// NULLPOINTER EXCEPTION

    while(iterator.hasNext()){

       System.out.println(iterator.next().toString());
    }
    this.menu.resetStudent();
    }

    }
 }

最佳答案

您的StudentModel变量可能为空。您发布的代码并未显示该变量的初始化方式,因此我无法确切地告诉您您在做什么错,但是当您到达标记的行时,它必须为null。

在尝试使用该变量之前,应检查是否已正确初始化该变量。

09-28 15:04