如何在内部类中添加比较器?

时间:2012-09-16 13:02:30

标签: java inner-classes comparator

    public class Prerequisites {

        private class Course implements Comparator<Course> {
            public String name;
            public LinkedList<Course> requiredFor;
            public LinkedList<Course> prerequisites;

            Course(String name) {
                requiredFor = new LinkedList<Course>();
                prerequisites = new LinkedList<Course>();
                this.name = name;
            }

            @Override
            public int compare(Course c0, Course c1) {
                Pattern p = Pattern.compile("[A-Z]*");
                Matcher matcher0 = p.matcher(c0.name);
                Matcher matcher1 = p.matcher(c1.name);
                matcher0.find();
                matcher1.find();
                int courseNumber0 = Integer.parseInt(c0.name.substring(matcher0.end(),c0.name.length()));
                int courseNumber1 = Integer.parseInt(c1.name.substring(matcher1.end(),c1.name.length()));
                if(courseNumber0 > courseNumber1) {
                    return 1;
                }
                else if(courseNumber0 < courseNumber1) {
                    return -1;
                }
                else {
                    return matcher0.group().compareTo(matcher1.group());
                }
            }

            @Override
            public String toString(){
                return this.name;
            }
        }
    public void compare(String args[]) {
        Course c0 = new Course("CSE110");
        Course c1 = new Course("DSE110");
        LinkedList<Course> courses = new LinkedList<Course>();
        courses.add(c0);
        courses.add(c1);
        **Collections.sort(courses);** //gives compiler error

    }
 }

为什么为此内部类添加Collections.sort()不起作用?我无法从编译器错误中找出答案。

3 个答案:

答案 0 :(得分:5)

您可能需要to implement Comparable,而不是Comparator

这就是the Collections#sort method expects

public static <T extends Comparable<? super T>> void sort(List<T> list)

答案 1 :(得分:3)

您应该实施Comparable,而不是Comparator

答案 2 :(得分:1)

Collections.sort(courses);

- 如果是上面的内容,那么您要实现的是它要实现的java.lang.Comparable接口,而不是java.util.Comparator接口。

- 此外,当您需要仅根据一个属性对项目进行排序时,会使用Comparable Interface

但是,如果您想根据多个属性对项目进行排序,请执行java.util.Comparator Interface

Collections.sort(List l, Comparator<T> t);