日期:2014-05-20  浏览次数:20833 次

Collections类中的reverseOrder方法
我在LinkedList类中添加了引用类型的元素,使用Collections类中的reverseOrder方法反向排序,并迭代输出时报错,我想是不是我添加的是引用类型,程序并不能找出比较规则,所以我在下面又写了一个Comparator接口的实现类,想通过这个比较器设定一下规则,写完后又发现这个比较器作为参数不知道怎么传给LinkedList,因为LinkedList构造方法中没有传入Comparator类型的,不像TreeSet构造方法可以传Comparator类型。说的有点乱,请问怎么解决啊,可以复制代码运行一下,谢谢啦。
  public   class   CollectonsTest   {
public   static   void   main(String[]   args)   {
LinkedList   list   =   new   LinkedList();

list.add(new   Student(10));
list.add(new   Student(20));
list.add(new   Student(30));
list.add(new   Student(40));

Comparator   com   =   Collections.reverseOrder();
Collections.sort(list,   com);

for(Iterator   it   =   list.iterator();it.hasNext();){
Student   stu   =   (Student)it.next();
System.out.println(stu.score);
}
}
}
class   Student{
int   score;
Student(int   score){
this.score   =   score;
}
}
class   MyComparator   implements   Comparator{
@Override
public   int   compare(Object   o1,   Object   o2)   {
Student   s1   =   (Student)o1;
Student   s2   =   (Student)o2;
return   s1.score   -   s2.score;
}
}

------解决方案--------------------
Java code

public class CollectonsTest {
    public static void main(String[] args) {
        LinkedList<Student> list = new LinkedList<Student>();
        list.add(new Student(10));
        list.add(new Student(20));
        list.add(new Student(30));
        list.add(new Student(40));
        Comparator<Student> com = Collections.reverseOrder();
        Collections.sort(list, com);
        for (Iterator<Student> it = list.iterator(); it.hasNext();) {
            Student stu = (Student) it.next();
            System.out.println(stu.score);
        }
    }
}
class Student implements Comparable<Student>{
    int score;
    Student(int score) {
        this.score = score;
    }
    @Override
    public int compareTo(Student s) {
        return this.score - s.score;
    }
}