在Java中学习聚合时,我遇到了 NULLPointerException ,请帮我确定根本原因。 有3个班级。
机构。
package com.java.inheritance; import java.util.List; import java.io。*;
iTLB-loads
包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 。我哪里做错了。
答案 0 :(得分:2)
您需要在添加列表之前创建列表。
ArrayList
这里你要添加一个空列表,这会导致异常。尝试创建新的LinkedList
或List<Student> sciencestudents = new ArrayList<>();
List<Student> artstudents = new ArrayList<>();
。
List<Department> departmentlist = new ArrayList<>();
同样,您还需要创建一个部门列表。
{{1}}