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

StackOverflow https://stackoverflow.com/questions/4441609

  •  10-10-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution

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

OTHER TIPS

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top