简体   繁体   English

带有自定义比较器的Java排序列表

[英]Java Sort List with custom Comparator

I have my class : 我上课:

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);
        }

...

}

And i'm trying to sort an array of Vehicle with a custom comparator from the class: 我正在尝试使用来自类的自定义比较器对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());
        }

    }
}

But i get an error when I try to do this : 但是当我尝试执行此操作时出现错误:

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

Edit: MyListOfVehicle is a variable List<Vehicle> The error i get from NetBeans is : 编辑:MyListOfVehicle是变量List<Vehicle>我从NetBeans得到的错误是:

error: no suitable method found for sort(List,CompararVehicle) Arrays.sort(llVeh, new CompararVehicle()); 错误:找不到适合于sort(List,CompararVehicle)Arrays.sort(llVeh,new CompararVehicle())的合适方法; method Arrays.sort(T#1[],Comparator) is not applicable (cannot infer type-variable(s) T#1 方法Arrays.sort(T#1 [],Comparator)不适用(无法推断类型变量T#1

It's the fact that i already have a compareTo in my class "vehicle" interfering when I try to order the array with another standard? 这是事实,当我尝试使用另一种标准订购数组时,我的类“车辆”中已经存在compareTo? If so, how can i order by the new standard? 如果是这样,我如何按新标准订购?

Your MyListofVehicle is a List (List) not an array so uyou cant use Arrays.sort method try this 您的MyListofVehicle是一个列表 (列表)而不是数组,因此您不能使用Arrays.sort方法尝试这个

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

or you can do something like this 或者你可以做这样的事情

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM