问题
I am learning how to use Comparator interface in java and I am trying to write my own Comparator which would compare Integers differently ( e.g 3>5 ). I have a problem with it, could someone tell what is wrong with my code?
import java.util.*;
import java.lang.*;
class MyComparator<Integer> implements Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
if(a.compareTo(b)>0)
return -1;
else if(a.compareTo(b)<0)
return 1;
else
return 0;
}
}
The compilator cannot find compareTo(Integer).
回答1:
Change
class MyComparator<Integer> implements Comparator<Integer>
to
class MyComparator implements Comparator<Integer>
In the first case you're declaring a type parameter which is shadowing java.lang.Integer
.
来源:https://stackoverflow.com/questions/25610170/comparing-two-integers-with-my-own-comparator