0

I am getting an int cannot be dereferenced error and I'm not sure how to fix it.

public class ComparatorYearLevel implements Comparator<CourseDomain> {
    @Override
    public int compare(CourseDomain one, CourseDomain two) {
        return one.getYearLevel().compareTo(two.getYearLevel());
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Can you tell us what the meaning of the year level is, and what sorts of values it can take on? How should we be logically comparing them? – Tim Biegeleisen Feb 17 '17 at 04:04
  • Your getYearLevel might be returning primitive that is not an object which yield this error as you can only comapare objects using `compareTo` method – hashmap Feb 17 '17 at 04:21

2 Answers2

0

Here is one option:

@Override
public int compare(CourseDomain one, CourseDomain two) {
    int a = one.getYearLevel();
    int b = two.getYearLevel();
    return a > b ? 1 : a < b ? -1 : 0;
}

You could also return this:

return Integer.compare(a, b);

But the ternary expression should perform better.

Further reading: compareTo with primitives -> Integer / int

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
-1

Your problem is that one.getYearLevel() is returning int. Since that's not an object type, you can't go calling methods on it.

You could write

return Integer.valueOf(one.getYearLevel()).compareTo(two.getYearLevel());

This explicitly converts your int to and Integer, on which it is possible to call the compareTo method.

Another alternative would be just to write

return one.getYearLevel() - two.getYearLevel();

which meets the requirements of compareTo, provided the int values aren't large enough to risk integer overflow.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110