【发布时间】:2017-03-23 01:59:29
【问题描述】:
我有我的课:
public class Vehicle implements Comparable<Vehicle> {
....
@Override
public int compareTo(Vehicle o) {
if (o.dataMatricula.compareTo(dataMatricula) ==0){
return matricula.compareTo(o.matricula);
}
else {
return o.dataMatricula.compareTo(dataMatricula);
}
...
}
我正在尝试使用类中的自定义比较器对 Vehicle 数组进行排序:
class CompararVehicle implements Comparator<Vehicle> {
@Override
public int compare(Vehicle o1, Vehicle o2) {
if (o1 == o2) {
return 0;
}
if(o2.getDataMatricula().compareTo(o1.getDataMatricula())==0){
if(o1.getMatricula().compareTo(o2.getMatricula())==0){
return 0;
}
else {
return o1.getMatricula().compareTo(o2.getMatricula());
}
}
else {
return o2.getDataMatricula().compareTo(o1.getDataMatricula());
}
}
}
但是当我尝试这样做时出现错误:
Arrays.sort(MyListofVehicle, new CompararVehicle());
编辑:MyListOfVehicle 是一个变量 List<Vehicle>
我从 NetBeans 得到的错误是:
错误:找不到合适的方法 排序(列表,比较车辆) Arrays.sort(llVeh, new CompararVehicle()); 方法 Arrays.sort(T#1[],Comparator) 不适用 (无法推断类型变量 T#1
事实上,当我尝试使用另一个标准订购数组时,我的班级“车辆”中已经有一个 compareTo 干扰?如果是这样,我如何按新标准订购?
【问题讨论】:
-
Arrays.sort只能对数组排序,List不能。也许您打算使用Collections.sort。 -
MyListofVehicle是一种类型吗?它的拼写就像一个,而不是一个变量。如果它是一个(拼写错误的)变量,它的类型是什么?该错误说明了有关List的内容,但您要求的是一种数组。您不能使用对数组进行排序的方法对非数组的内容进行排序。 -
这是车辆清单,已编辑!