【发布时间】:2017-04-29 17:28:55
【问题描述】:
我正在尝试使用比较器接口按降序对列表进行排序。但是这些值不是按降序排序的。不知道我在这里做错了什么。
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找到
谁能告诉我为什么降序排序不起作用?
【问题讨论】: