Java:解析List并在Array中设置它时获取NullPointerException

时间:2012-02-24 09:49:41

标签: java

这是我的Java程序,我在for循环中设置Objects with,如图所示

ArrayList list = new ArrayList();
for(int j = 0;j<=4;j++)
{
Student student = new Student();
studunt.name="Ravi";
list.add(student);
}

然后我需要解析此List并将其设置在StudentResponse(由学生[]组成)

StudentResponse  response = new StudentResponse();

    for (int in = 0; in < list.size(); in++) {
    {
    Student data = (TopListsQuoteData) list.get(in);
    response. student[in] = data;
    }

这是我的StudentResponse课程

public class StudentResponse 
{
public  Student[] student;
}

我在这一行得到一个NullPointerException 响应。 student [in] = data;

请帮助,谢谢。

5 个答案:

答案 0 :(得分:6)

初始化!

public  Student[] student = new Student[100];

可能是。

public StudentResponse(int capacity){
   this.student = new Student[capacity];
}

答案 1 :(得分:2)

您需要先初始化阵列,然后才能使用它。像这样:

StudentResponse  response = new StudentResponse();
response.student = new Student[list.size()];
for (int in = 0; in < list.size(); in++) {
{
    Student data = (TopListsQuoteData) list.get(in);
    response. student[in] = data;
}

另外我建议使用列表的迭代器而不是按索引访问项目。这有效,但我觉得它不是那么干净,绝对不那么有效。

答案 2 :(得分:1)

您是否在StudentResponse的构造函数中初始化数组?像

这样的东西
public StudentResponse(int numberOfStudents) {
   this.student = new Student[numberOfStudents];
}

您可能希望将学生数组切换为另一种列表 - 列表通常可以更好地使用。

public class StudentResponse {
    private List<Student> students;

   public StudentResponse() {
      this.students = new ArrayList<Student>();
   }

   public void addStudent(Student student) {
       this.students.add(student);
   }

   public List<Student> getStudents() {
       return this.students;
   }

}

现在您可以像这样修改代码:

StudentResponse  response = new StudentResponse();

for (int in = 0; in < list.size(); in++) {
{
Student data = (TopListsQuoteData) list.get(in);
response.addStudent(data);
}

答案 3 :(得分:0)

您的代码中有拼写错误

Student student = new Student();
studunt.name="Ravi";

但我认为你想要:

Student student = new Student();
student.name="Ravi";

答案 4 :(得分:0)

如果您需要的只是列表的副本,但是作为数组:

response.student = list.toArray(new Student[list.size()]);