我想知道爲什麼在嘗試排序列表後出現錯誤。 當我嘗試對包含「學生」對象的列表進行排序時發生錯誤。使用Collections.sort時發生錯誤()
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()));
}
}
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;
}
}
interface Comparable<Student>{
int CompareTo(Student otherStudent);
String toString();
}
的錯誤是:
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>>
我不明白什麼是錯誤的手段和如何解決它。您的意見將非常感謝。