-1
public static ArrayList<Integer> getStudentClasses(Student student, ArrayList<Integer>[] classesXstudents) {
      ArrayList<Integer> classes = new ArrayList<Integer>();
      for (int i = 0; i < classesXstudents.length; i++) {
        for (int j = 0; j < classesXstudents[i].size(); j++) {
          if (classesXstudents[i].get(j) == student.getID()) {
            classes.add(i+1);
          }
        }
      }
      return classes;
  }

throws NullPointerException at the line

  for (int j = 0; j < classesXstudents[i].size(); j++) {

which I'm assuming means classesXstudents[i].size() is null at some point. classesXstudents is an array of ArrayList objects. How should I debug this case?

Luca Putzu
  • 1,438
  • 18
  • 24
John314
  • 7
  • 1
  • 2

3 Answers3

1

How about something like this.

if (classesXstudents[i] != null){
   for (int j = 0; j < classesXstudents[i].size(); j++) {
       //....
   }
} else {
   //
}

Some of your elements are probably null, you should probably check where they're initialized. It might just be that you forgot to initialize one of them.

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
0

What that means is that some element of the classesXstudents[i] array is null.

Look at how that array is filled. Search for cases where null might be inserted, or when some element might be left unassigned (default value is null), perhaps at the end of the array.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
0

This is happening because some elements of your ArrayList<Integer> classesXstudents[i] are null.

You can fix this problem by checking if the element whose size you are asking for actually isn't null.

 if (classesXstudents[i] != null) {
      // Your for-loops and rest of the code here
 }

Adding the above snippet will check to see if the element is null (say you forgot to initialize it) or not. You can incorporate this in your code as follows:

public static ArrayList<Integer> getStudentClasses(Student student, ArrayList<Integer>[] classesXstudents) 
{
    ArrayList<Integer> classes = new ArrayList<Integer>();
    for (int i = 0; i < classesXstudents.length; i++) {
        if (classesXstudents[i] != null) // This statement is what you need to add

            for (int j = 0; j < classesXstudents[i].size(); j++) {
                if (classesXstudents[i].get(j) == student.getID()) {
                    classes.add(i+1);
                }
            }
   }
   return classes;
}
Madhav Datt
  • 1,065
  • 2
  • 10
  • 25