java - 按降序对对象列表进行排序

标签 java collections comparator

我想按降序对列表对象进行排序,并面临 classCastException。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

     class Student implements Comparator<Student>{
     private int id;
         private String name;

        public Student(int id, String name){
    this.id = id;
    this.name = name;
}

public int getId(){
    return id;
}
public String getName(){
    return name;
}

}

public class CollectionSearchDemo {


public static void main(String[] args) {

    List<Student> list = new ArrayList<Student>();
    list.add(new Student(3, "ouier"));
    list.add(new Student(2, "fdgds"));
    list.add(new Student(7, "kiluf"));
    list.add(new Student(1, "6trfd"));
    list.add(new Student(8, "hjgas"));
    list.add(new Student(5, "ewwew"));

    Collections.sort(list, new Comparator<Student>() {

        @Override
        public int compare(Student arg0, Student arg1) {

            return arg0.getId() - arg1.getId();
        }
    });

    Iterator iterator = list.iterator();
    while(iterator.hasNext()){
        Student student = (Student) iterator.next();
        System.out.print(student.getId()+":"+student.getName()+" ");
    }

    System.out.println("\nSorting in reverse order:");

//  Collections.reverse(list);
    Comparator<Student> collections = Collections.reverseOrder();
    Collections.sort(list, collections);     // here getting classCastException.

    Iterator iterator1 = list.iterator();
    while(iterator1.hasNext()){
        Student student = (Student) iterator1.next();
        System.out.print(student.getId()+":"+student.getName()+" ");
    }
}

}

想了解一些事情。 1)什么是差异投注 Collection.reverse(列表) 和 比较器集合 = Collections.reverseOrder(); Collections.sort(列表, 集合); 2)为什么我面临 classCastException。

最佳答案

您需要使用reverse()方法,

reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

所以ClassCastException

关于java - 按降序对对象列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14885809/

相关文章:

java - GWT 代码服务器使用 Maven 原型(prototype)在新生成的项目中找不到模块

c# - 我什么时候应该为我的类型定义哈希码函数?

java - 在 for 循环初始化时弹出队列的元素最终会始终弹出相同的元素

java - 我如何比较自定义树集实现中的两个对象?

java - onReceivedClientCertRequest 未被调用

java - 通过参数名称引用成员?

c# - 无法在 C++ CLI 中维护指针集合

java - Streams 中的 map() 如何工作以及当参数是 Collection 时如何使用它

java - Collections.sort 是否保持相等元素的顺序?

java - 使用 Comparable 和 Comparator 比较泛型类型