[英]Java Sort List with custom Comparator
我上課:
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得到的錯誤是:
錯誤:找不到適合於sort(List,CompararVehicle)Arrays.sort(llVeh,new CompararVehicle())的合適方法; 方法Arrays.sort(T#1 [],Comparator)不適用(無法推斷類型變量T#1
這是事實,當我嘗試使用另一種標准訂購數組時,我的類“車輛”中已經存在compareTo? 如果是這樣,我如何按新標准訂購?
您的MyListofVehicle是一個列表 (列表)而不是數組,因此您不能使用Arrays.sort方法嘗試這個
Collections.sort(MyListofVehicle, new CompararVehicle());
或者你可以做這樣的事情
Arrays.sort(MyListofVehicle.toArray(new Vehicle[0]), new CompararVehicle());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.