我在嘗試使用比較器接口以降序對列表進行排序。但是這些值不是按降序排列的。不知道我在這裏做錯了什麼。java - 使用比較器以降序排序
public class Student {
int rollNo;
String name;
int age;
public Student(int RollNo, String Name, int Age){
this.rollNo = RollNo;
this.name = Name;
this.age = Age;
}
}
public class AgeComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Ascending
//return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Descending
}
}
public class Comparator_Sort {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(5978,"Vishnu", 50));
al.add(new Student(5979,"Vasanth", 30));
al.add(new Student(5980,"Santhosh", 40));
al.add(new Student(5981,"Santhosh", 20));
al.add(new Student(5982,"Santhosh", 10));
al.add(new Student(5983,"Santhosh", 5));
Collections.sort(al, new AgeComparator());
for(Student s : al){
System.out.println(s.rollNo+" "+s.name+" "+s.age);
}
}
}
我可以按升序排序列表,而我無法做到這一點的降序
return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Sorted in Ascending
return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Not sorted in Descending
比較文檔 - 返回:負整數,零或者作爲第一個參數的正整數小於,等於或大於第二個參數。來源是從here
誰能告訴我爲什麼降序排序不工作?
如果ü校驗i所提供的源,它遵循以下標準 – Aishu
-1:O1 O2 –
Aishu
我按照相同的方法,但按降序排序不起作用 – Aishu