【问题标题】:Sorting an list of object in descending order按降序对对象列表进行排序
【发布时间】:2013-02-14 23:15:01
【问题描述】:

我想按降序对列表对象进行排序,并面对 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) 有什么区别 bet'n Collection.reverse(列表) 和 比较器集合 = Collections.reverseOrder(); Collections.sort(列表,集合); 2)为什么我面临classCastException。

【问题讨论】:

  • 你得到一个ClassCastException,因为Student应该实现Comparable&lt;Student&gt;,而不是Comparator&lt;Student&gt;
  • 是的。它有效。你能告诉我更多的描述吗?它将帮助我更好地理解这个概念
  • Comparator 比较事物。 Comparable 可以与其他事物进行比较。
  • 嗨,我想在这个列表上执行 binarySearch。我遇到了一个异常。stackoverflow.com/questions/14896120/…。请帮帮我。我请求你

标签: java collections comparator


【解决方案1】:

你需要使用reverse()方法,

reverseOrder()

返回一个比较器,该比较器对实现 Comparable 接口的对象集合施加自然顺序的逆向。

所以ClassCastException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 2016-10-18
    • 1970-01-01
    • 2023-03-21
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多