Java:使用Array.sort()错误 - java.lang.ClassCastException:学生无法强制转换为java.lang.Comparable

时间:2010-12-14 16:37:51

标签: java compareto

我正在尝试编写一个程序,用于对一组对象进行排序。

有谁知道我收到此错误的原因?代码片段包括在下面!

学生对象

/* Class for storing students */
public class Student {
  private String name;
  private int mark;

  //Constructor
  public Student(String gName, int gMark) {
    name = gName;
    mark = gMark;
  }

  //Get Mark  
    public int getMark() {
    return mark;
  }
  //Compare to
   public int compareTo(Student gStudent) {
    return this.mark - (int) gStudent.getMark();
  }

}

将这些学生放入阵列标记(学生对象);

  //Create array
    Student[] marks = new Student[numberOfMarks];

    //Input for each student
    for (int cItem = 0; cItem < numberOfMarks; cItem++) {
        System.out.print("Please enter student number "+(cItem + 1)+"'s name: ");
        String cName = markScanner.nextLine();
        System.out.print("Please enter "+cName+"'s mark: ");
        int cMark = markScanner.nextInt();
        //Skip line
        markScanner.nextLine();
        marks[cItem] = new Student(cName, cMark);
    }

然而,排序似乎不起作用

//Sorting
Arrays.sort(marks);

并产生错误:

Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    at MarkAnalysis.main(MarkAnalysis.java:33)

并产生错误

2 个答案:

答案 0 :(得分:7)

public class Student implements Comparable<Student> {
  ...
}

答案 1 :(得分:3)

public class Student implements Comparable<Student> { }

另外,你的compareTo()方法有点不正统。通常,您需要这些内容:

     public int compareTo(Student gStudent) {
        if(this.mark > gStudent.getMark()) return 1;
        if(this.mark < gStudent.getMark()) return -1;
        return 0;
    }