将两个整数与我自己的比较器进行比较 [英] Comparing two Integers with my own Comparator
本文介绍了将两个整数与我自己的比较器进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习如何在Java中使用Comparator接口,并且试图编写自己的Comparator,该比较器会以不同的方式比较Integer(例如3> 5)。我有问题,有人可以告诉我我的代码出了什么问题吗?
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;
}
}
编译器找不到compareTo(Integer)。
The compilator cannot find compareTo(Integer).
推荐答案
更改
class MyComparator<Integer> implements Comparator<Integer>
至
class MyComparator implements Comparator<Integer>
在第一种情况下,您声明类型参数,它正在掩盖 java.lang.Integer
。
In the first case you're declaring a type parameter which is shadowing java.lang.Integer
.
这篇关于将两个整数与我自己的比较器进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文