在Java聚合中面对NULL指针异常

时间:2018-04-21 19:06:09

标签: java

在Java中学习聚合时,我遇到了 NULLPointerException ,请帮我确定根本原因。 有3个班级。

  1. 学生
  2. 系。
  3. 机构。

    package com.java.inheritance;     import java.util.List;     import java.io。*;

    iTLB-loads
  4. 包com.java.inheritance;

    public class Department {
    
        private String name;
        private List<Student> listofstudents;
    
        Department(String name,List<Student> listofstudents){
    
            this.name =name;
            this.listofstudents = listofstudents;
        }
    
        public List<Student> getStudents(){
    
            return this.listofstudents;
        }
    
    
    }
    

    现在我在另一个类MainClass中调用它们。

    public class Student {
    
        private String name;
        private int id;
        private String Department;
    
        Student(String name,int id,String Department){
    
            this.name =name;
            this.id= id;
            this.Department = Department;
    
        }
    
    }
    
    
    
        package com.java.inheritance;
        import java.util.List;
    
        public class Institute {
    
           private String institureName;
           private List<Department> listofDept;
    
          public Institute(String institureName,List<Department> listofDept){
               this.institureName = institureName;
               this.listofDept = listofDept;
           }
    
          public List<Department> getDepartments(){
              return this.listofDept;
          }
    
          // Get total number of Student in a Institute.
    
          public int gettotalnoofStudents(){
              int numberofStudent = 0;
              List<Student> listofStudent=null;
              for (Department dept:listofDept){
                  listofStudent = dept.getStudents();
                  for (Student student:listofStudent){
    
                      numberofStudent++;  
                  }
    
              }
    
              return numberofStudent;
          }
    
    
        } // End of Institute
    

    但此时我得到 NULLpointerException 。我哪里做错了。

1 个答案:

答案 0 :(得分:2)

您需要在添加列表之前创建列表。

ArrayList

这里你要添加一个空列表,这会导致异常。尝试创建新的LinkedListList<Student> sciencestudents = new ArrayList<>(); List<Student> artstudents = new ArrayList<>();

List<Department> departmentlist = new ArrayList<>();

同样,您还需要创建一个部门列表。

{{1}}