使用Collections.sort()时出错

use*_*625 1 java sorting comparable comparator

我想知道为什么我在尝试对List进行排序后出现错误.当我尝试对包含"Student"对象的列表进行排序时,会发生错误.

import java.lang.reflect.Array;
import java.util.*;
import java.util.ArrayList;

public class mainProgram {
    public static void main(String[] args) {
        List<Student> classStudents = new ArrayList<Student>();

    //Add 4 students to List
        classStudents.add(new Student("Charles", 22));
        classStudents.add(new Student("Chris", 25));
        classStudents.add(new Student("Robert", 23));
        classStudents.add(new Student("Adam", 21));

    //sort and print
        Collections.sort(classStudents);    //Why does this not work?
        System.out.println("classStudent(Sorted) ---> "
        + Arrays.toString(classStudents.toArray()));
    }
}
Run Code Online (Sandbox Code Playgroud)
class Student implements Comparable<Student>{
    // fields
    private String name;
    private int age;

    //Constructor
    public Student(String name, int age){ 
        name = name;
        age = age;
        }
    //Override compare
    public int CompareTo(Student otherStudent){
        if(this.age == otherStudent.age){
            return 0;
        } else if(this.age < otherStudent.temp){
            return -1;
        } else{
            return 1;
        }
    }

    //Override toString
    public String toString(){
        return this.name + " " + this.age;
    }
}
Run Code Online (Sandbox Code Playgroud)
interface Comparable<Student>{
    int CompareTo(Student otherStudent); 
    String toString();
}
Run Code Online (Sandbox Code Playgroud)

错误是:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Student>). The inferred type Student is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>
Run Code Online (Sandbox Code Playgroud)

我不明白错误意味着什么以及如何解决它.非常感谢您的意见.

Psh*_*emo 8

基于错误消息可能不是那么明显,但是如果你看一下你的文档,Collection.sort请发现这个方法(比如其他标准API方法)需要实现已在API接口定义的实例列表,在本例中是java.lang.Comparable.

所以不要试图创建自己的Comparable界面.请记住,如果某些方法需要某种类型,则必须已在某处定义此类型(否则具有此类方法的类将无法编译,因为方法无法使用某些未知/未定义类型).

另外比较中定义的java.util.Comparable方法compareTo不是CompareTo(Java区分大小写,因此这些方法不会被视为相等).


其他问题是


归档时间:

查看次数:

4268 次

最近记录:

10 年,4 月 前