I believe I am making a really simple mistake/ overlooking something trivial.
import java.util.Comparator;
public class NaturalComparator {
You accidentally created a generic type parameter Integer
which has nothing to do with the Integer
class, and you didn't implement Comparator
. Try
public class NaturalComparator implements Comparator<Integer>
Placing an identifier in <>
on the class declaration declares a generic type parameter, but placing an identifier in <>
on the implements/extends clause is a passing a type argument.
You are shadowing the type java.lang.Integer
with a type parameter variable you decided to name Integer
.
Your code is equivalent to
public class NaturalComparator<T> {
public int compare(T o1, T o2) {
return o1.intValue() - o2.intValue();
}
}
Which obviously doesn't compile since Object
(the bound of T
) doesn't declare a intValue()
method.
What you want is
public class NaturalComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1.intValue() - o2.intValue();
}
}
in which case java.lang.Integer
is used as a type argument.