【发布时间】:2015-07-01 21:50:08
【问题描述】:
我想知道为什么在尝试对列表进行排序后出现错误。 当我尝试对包含“学生”对象的列表进行排序时发生错误。
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>>
我不明白错误的含义以及如何修复它。非常感谢您的意见。
【问题讨论】:
标签: java sorting comparator comparable