Gus
Gus

Reputation: 33

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

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

Upvotes: 3

Views: 11437

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280142

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

Upvotes: 13

Related Questions