开发者

Java: Using Array.sort() error - java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable

开发者 https://www.devze.com 2023-01-31 02:17 出处:网络
I am trying to write a program for my course that sorts an array of objects. Does anyone know why I am getting this error? Snippets of code included below!

I am trying to write a program for my course that sorts an array of objects.

Does anyone know why I am getting this error? Snippets of code included below!

Student object

/* 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();
  }

}

And putting these students in the array marks (of student objects);

  //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);
    }

However the sort doesn't seem to work

//Sorting
Arrays.sort(marks);

And produces the error:

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)

And produce the error


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


public class Student implements Comparable<Student> { }

Also, your compareTo() method is a bit unorthodox. Typically, you want something along these lines:

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

精彩评论

暂无评论...
验证码 换一张
取 消