user663724
user663724

Reputation:

Java : Getting NullPointerException while parsing the List and setting it inside a Array

This is my Java program , where i am setting the Objects with in the for loop as shown

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

Then i need to parse this List and set it inside a StudentResponse ( Which is consisting of a Student[])

StudentResponse  response = new StudentResponse();

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

This is my StudentResponse class

public class StudentResponse 
{
public  Student[] student;
}

I am getting a NullPointerException at this line response. student[in] = data;

Please help , Thanks .

Upvotes: 0

Views: 271

Answers (5)

user1230540
user1230540

Reputation:

If all you need is a copy of the list, but as an array:

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

Upvotes: 0

blackmamba
blackmamba

Reputation: 141

And you have a spelling Error in your code

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

but I think you want:

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

Upvotes: 0

user130076
user130076

Reputation:

Do you initialise your array in the constructor of StudentResponse? Something like

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

You may want to switch out the student array as another kind of list - lists are generally much nicer to work with.

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;
   }

}

Now you can modify your code like so:

StudentResponse  response = new StudentResponse();

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

Upvotes: 1

Steven
Steven

Reputation: 2477

You need to initialize the array before you can use it. Something like this:

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;
}

Also i would suggest to use the iterator of the list instead of accessing the items by index. This works, but I feel it's not so clean and definitely not as efficient.

Upvotes: 1

Nishant
Nishant

Reputation: 55866

Initialize!

like

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

may be.

or

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

Upvotes: 6

Related Questions