Java:绑定不匹配:使用比较器时出错
我正在尝试一个小代码,使用Comparator对学生名单中的卷号进行排序。但我在这一行遇到编译时错误:Java:绑定不匹配:使用比较器时出错,java,comparator,Java,Comparator,我正在尝试一个小代码,使用Comparator对学生名单中的卷号进行排序。但我在这一行遇到编译时错误: Collections.sort(l); 下面是我的测试代码: package test; import java.util*; public class StudentUsingComparator implements Comparator<StudentUsingComparator> {
Collections.sort(l);
下面是我的测试代码:
package test;
import java.util*;
public class StudentUsingComparator implements
Comparator<StudentUsingComparator> {
int roll;
String name;
public StudentUsingComparator(int roll, String name) {
this.name = name;
this.roll = roll;
}
@Override
public int compare(StudentUsingComparator s1, StudentUsingComparator s2) {
return s1.roll - s2.roll;
}
public static void main(String[] args) {
StudentUsingComparator student1 = new StudentUsingComparator(10, "ab");
StudentUsingComparator student2 = new StudentUsingComparator(30, "cd");
StudentUsingComparator student3 = new StudentUsingComparator(20, "bc");
List<StudentUsingComparator> l = new ArrayList<StudentUsingComparator>();
l.add(student1);
l.add(student2);
l.add(student3);
System.out.println("unsorted collection is: " + l);
Collections.sort(l); //m getting error in this line
System.out.println("sorted collection is: " + l);
}
}
封装测试;
导入java.util*;
使用Comparator实现的公共类学生
比较器{
整流罩;
字符串名;
使用比较器的公共学生(整数卷,字符串名){
this.name=名称;
this.roll=roll;
}
@凌驾
公共整数比较(StudentUsingComparator s1,StudentUsingComparator s2){
返回s1.roll-s2.roll;
}
公共静态void main(字符串[]args){
StudentUsingComparator student1=新学生UsingComparator(10,“ab”);
StudentUsingComparator student2=新学生UsingComparator(30,“cd”);
StudentUsingComparator student3=新学生UsingComparator(20,“bc”);
列表l=新的ArrayList();
l、 增加(学生1);
l、 增加(学生2);
l、 增加(学生3);
System.out.println(“未排序的集合为:“+l”);
Collections.sort(l);//我在此行中遇到错误
System.out.println(“已排序的集合为:“+l”);
}
}
错误消息显示:
绑定不匹配:集合类型的泛型方法排序(列表)不适用于参数列表()。推断类型StudentUsingComparator不是有界参数的有效替代品>
您混淆了
Comparable
和Comparator
。具有内在顺序的类应该实现compariable
,然后可以使用collections.sort(l)
。使用Collections.sort(l,c)
时,c
应该实现Comparator
,它定义了一个不同于内部的外部顺序。您的代码混合了两个概念:
可比的学生类,然后可以使用集合。排序(l)
对列表l
进行排序
学生
(可以是可比的
)之外,您还可以定义一个实现比较器
的额外类,并使用集合。使用列表l
和比较器c
对(l,c)
进行排序Student
实现Comparator
(然后继续执行2)。但这是完全不可能的,因为您的对象有一个自然的顺序-然后您应该使用Comparable
和案例1,或者它们没有,然后定义顺序应该转到一个单独的比较器
-类