-1

Why won't it compile? I am trying to sort a list of school courses by one int property: courseLevel, in ascending order.

I have a class named UCFCourse with several objects courses[]. I am assigning the property values to each object while incrementing x.Here is my code in my main:

courses[x] = new UCFCourse(courseCode, courseLevel, courseHours, replaceString, eitherCourse);

This is where I added my courses[].If I print out ListOne I get a massive list containing all my courses.

List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
        for (int i = 0; i < courses.length; i++) {
            ListOne.add(courses[i]);
        }


//I added all my courses[] to a List
List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
Collections.sort(ListOne, new CourseComparator());

Comparator class:

import java.util.Comparator;

public class CourseComparator implements Comparator<UCFCourse> {
    public int compare(UCFCourse Course1, UCFCourse Course2) {
        return Course1.getCourseLevel() - Course2.getCourseLevel();
    }
}

When I initially created my object it looked like this:

UCFCourse[] courses = new UCFCourse[75];

Not sure if this bit is relevant since I added all of them into an Array list already but I want to be thorough.

Errors:

Exception in thread "main" java.lang.NullPointerException
OneU
  • 85
  • 6

3 Answers3

1
List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
<add your items to list here>
Collections.sort(ListOne, new CourseComparator());

As this code stands, you are sending a blank list to the Comparator. If you are sure you have items in the list, check that the Course1 and Course2 items being passed actually have a value. You can test quickly by taking the 'getCourseLevel()' off of them and returning the values back to the calling method.

Joe
  • 37
  • 4
  • OP said `ListOne` was populated from the array. Assuming the array is full of nulls, trying to call `getCourseLevel()` will throw the same exception. – shmosel Jan 04 '17 at 22:57
1

You're just creating a new object on your ListOne variable and that variable is still empty that's why you're getting a NullPointerException.

And try to use a camel case so that you can identify your code properly.

1

From the code snippet you've provided I can tell you the following:

UCFCourse[] courses = new UCFCourse[75]; 

only creates an array full with null objects. Lopping through this array and adding each object into your ArrayList will not instantiate them.

List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
    for (int i = 0; i < courses.length; i++) {
        ListOne.add(courses[i]);
    }

The consequence is that the Comparator#compare(UCFCourse c1, UCFCourse c2) method parameters, c1 and c2, will be null, which leads to the NullPointerException.

What you need to do before adding them to the ArrayList is to create your UCFCourse objects, e.g.:

        for (int i = 0; i < courses.length; i++) {
            courses[i] = new UCFCourse(...);
        }