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:
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 :
error: no suitable method found for sort(List,CompararVehicle) Arrays.sort(llVeh, new CompararVehicle()); method Arrays.sort(T#1[],Comparator) is not applicable (cannot infer type-variable(s) 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? 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
Collections.sort(MyListofVehicle, new CompararVehicle());
or you can do something like this
Arrays.sort(MyListofVehicle.toArray(new Vehicle[0]), new CompararVehicle());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.