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

Bun*_*bit 1 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

    }
 }
Run Code Online (Sandbox Code Playgroud)

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

ass*_*ias 5

你可能想要实现Comparable,而不是Comparator.

这就是Collections#sort方法需要:

public static <T extends Comparable<? super T>> void sort(List<T> list)
Run Code Online (Sandbox Code Playgroud)