Comparing two Integers with my own Comparator

孤街醉人 提交于 2019-12-24 04:44:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!