Java: Utilisation erreur Array.sort () - java.lang.ClassCastException: L'étudiant ne peut pas être jeté à java.lang.Comparable

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

  •  10-10-2019
  •  | 
  •  

Question

Je suis en train d'écrire un programme pour mon cours qui trie un tableau d'objets.

Quelqu'un sait pourquoi j'obtiens cette erreur? Bribes de code inclus ci-dessous!

Objet étudiant

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

}

Et mettre ces élèves dans les marques de tableau (des objets étudiants);

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

Cependant le genre ne semble pas au travail

//Sorting
Arrays.sort(marks);

Et produit l'erreur:

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)

Et produire l'erreur

Était-ce utile?

La solution

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

Autres conseils

public class Student implements Comparable<Student> { }

En outre, votre méthode compareTo () est un peu orthodoxe bits. En règle générale, vous voulez quelque chose le long de ces lignes:

     public int compareTo(Student gStudent) {
        if(this.mark > gStudent.getMark()) return 1;
        if(this.mark < gStudent.getMark()) return -1;
        return 0;
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top