2010-12-14 59 views
1

我想爲我的課程編寫一個排序對象數組的程序。Java:使用Array.sort()錯誤 - java.lang.ClassCastException:學生不能轉換爲java.lang.Comparable

有誰知道我爲什麼得到這個錯誤?下面的代碼片段!

Student對象

/* 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) 

而產生錯誤

回答

7
public class Student implements Comparable<Student> { 
    ... 
} 
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; 
    } 
相關問題