【问题标题】:Java Sort List with custom Comparator带有自定义比较器的 Java 排序列表
【发布时间】: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&lt;Vehicle&gt; 我从 NetBeans 得到的错误是:

错误:找不到合适的方法 排序(列表,比较车辆) Arrays.sort(llVeh, new CompararVehicle()); 方法 Arrays.sort(T#1[],Comparator) 不适用 (无法推断类型变量 T#1

事实上,当我尝试使用另一个标准订购数组时,我的班级“车辆”中已经有一个 compareTo 干扰?如果是这样,我如何按新标准订购?

【问题讨论】:

  • Arrays.sort 只能对数组排序,List 不能。也许您打算使用Collections.sort
  • MyListofVehicle 是一种类型吗?它的拼写就像一个,而不是一个变量。如果它是一个(拼写错误的)变量,它的类型是什么?该错误说明了有关List 的内容,但您要求的是一种数组。您不能使用对数组进行排序的方法对非数组的内容进行排序。
  • 这是车辆清单,已编辑!

标签: java arrays sorting


【解决方案1】:

您的 MyListofVehicleList(列表)而不是 数组 所以你不能使用 Arrays.sort 方法 试试这个

Collections.sort(MyListofVehicle, new CompararVehicle());

或者你可以这样做

Arrays.sort(MyListofVehicle.toArray(new Vehicle[0]), new CompararVehicle());

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 2021-02-22
    • 2017-03-21
    • 2013-11-04
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2023-03-22
    • 2020-07-09
    相关资源
    最近更新 更多