你能帮我解决我的对象类数组的问题吗?每次运行该程序时,我都会遇到空指针问题。这是代码。
List<Student> listPerson = new ArrayList<>();
Student[] stud = null;
int counter = 0;
ResultSet rs = DBMSConnection.GetDetails();
while(rs.next()){
stud[counter] = new Student();
stud[counter].setFirst_name(rs.getString("first_name"));
stud[counter].setLast_name(rs.getString("last_name"));
stud[counter].setAddress(rs.getString("address"));
counter++;
}
for( int i = 0 ; i < counter ; i++){
listPerson.add(stud[i]);
}
这是您添加到其他答案中的修改
我真正想要的是像这样的人。
Student stud = new Student();
stud.firstname = "john";
stud.lastname = "doe";
Student stud2 = new Student();
stud2.firstname = "Mike";
stud2.lastname = "doe";
List<Student> list = new ArrayList<>();
list.add(stud);
list.add(stud2);
注意:有没有办法可以在循环内实例化 Student Stud;例如。
int record = 100;
Student[] sa = null;
for(int i = 0; i<record; i++){
sa[i] = new Student[]; //instantiate Objects on the fly
list.add(sa[i]);
}
我想将所有第一条记录分配到第一个对象实例中,例如stud具有第一条记录的值std2具有第二条记录并将其传递到列表。
最佳答案
你的数组是 null Student[] Stud = null;
因为它永远不会从 null 改变,但实际上你不需要数组
考虑
ResultSet rs = DBMSConnection.GetDetails();
while(rs.next()){
Student stud = new Student();
stud.setFirst_name(rs.getString("first_name"));
stud.setLast_name(rs.getString("last_name"));
stud.setAddress(rs.getString("address"));
listPerson.add(stud);
}
编辑
您可以稍后按如下方式迭代此 ArrayList
for (Student student: listPerson) {
System.out.println (student.getFirst());
}
关于java - 创建一个数组对象 Student 并将其添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41092733/