PriorityQueue: Student cannot be cast to java.lang.Comparable

不问归期 提交于 2019-11-30 21:32:02

问题


I'm using the PriorityQueue structure to get some fields set by the user, here is part of the code:

package gqg;

import java.util.Queue;

public class Student {
     //variables (ID, Name, ...), constructors, getters and setters...

Queue<Student> StudentQueue = new PriorityQueue<Student>();

public void Add() { //method to add the student at Queue
    for(int x=0; x<1; x++) {
        Student st = new Student();
        System.out.println("+---------------------------+\n"
                         + "|   Students Registration   |\n"
                         + "+---------------------------+");
        System.out.println("| Type the student's ID:");
        stu.setID(user.nextInt());
        System.out.println("| Type the student's name:");
        stu.setName(user.next());
        System.out.println("| Type the student's age:");
        stu.setAge(user.nextInt());
        //and other fields...

        StudentQueue.add(st);
    }
    System.out.println("Done. Student has been added successfuly\n");       
}

/* then I call Add(); in Menu();
 * this method also has Print(); Modify(); Eliminate(); those three works well
 * The only one problem is Add();
 */

public void Menu(){
    //... methods
}
}

There is no problem when I add only one "student", but the application throws this exception when I try to capture a second one

Exception in thread "main" java.lang.ClassCastException: gqg.Student cannot be cast to java.lang.Comparable     at
java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:633)    at
java.util.PriorityQueue.siftUp(PriorityQueue.java:629)  at
java.util.PriorityQueue.offer(PriorityQueue.java:329)   at
java.util.PriorityQueue.add(PriorityQueue.java:306)     at
gqg.Student.AddQueue(Student.java:374)  at
gqg.Student.Menu(Student.java:592)  at
gqg.MainClass.main(MainClass.java:7)

Can someone explain me where/why is the problem? I spent a lot of time looking for a solution in web and I couldn't find it, I need some help here... Tank you for helping me


回答1:


If you don't provide a custom Comparator, PriorityQueue uses natural ordering on the objects it holds. That is, it expects your objects to be Comparable to eachother. Your Student class doesn't seem to implement Comparable.

So two options:

  • Implement and provide a custom Comparator for comparing Student objects
  • Have your Student class implement Comparable<Student> with the appropriate logic


来源:https://stackoverflow.com/questions/26416258/priorityqueue-student-cannot-be-cast-to-java-lang-comparable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!