Comparing two Integers with my own Comparator

2019-07-20 05:38发布

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条回答
家丑人穷心不美
2楼-- · 2019-07-20 06:18

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.

查看更多
登录 后发表回答