Maude Poulin-labelle
Maude Poulin-labelle

Reputation: 35

Java PriorityQueue + class

Hi I am getting an error while trying to use PropertyQueue with java. I am a little unfamiliar with java and would appreciate getting a little bit of explanation with this error! Here is how my code look like roughly:

import java.util.*;
import java.io.*;

class Lecture{
    public Lecture(Strings){
        ...
    }
    //Then some getter and setter and function
}
class Room{
   Vector<Lecture> setLecture = new Vector<Lecture>();
   int end = 1;

   public void change_end(int c){
      end = end +c;
   }

  public void add_lecture(Lecture l){
     setLecture.add(l);
  }

}

public class interval_partioning{

  public static void main (String[] args) {
  // create priority queue
  PriorityQueue <Room>  classrooms = new PriorityQueue <Room> () ; 
  Room classroom1= new Room();
  Room classroom2= new Room();
  classrooms.add(classroom1);
  classrooms.add(classroom2);
 }
}

here is the error I get at this line : classrooms.add(classroom1);

Exception in thread "main" java.lang.ClassCastException: class Room cannot be cast to class java.lang.Comparable (Room is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')

What does it mean and how to fix it!

Thank you!

Upvotes: 1

Views: 262

Answers (1)

Kishore Sampath
Kishore Sampath

Reputation: 1001

Java priority queue's add method throws ClassCastException when you try to add a user defined class which does not implements the Comparable interface and override its equals method.

Java Priority Queue add method

In simpler terms, the priority queue inserts the object into the queue based on certain priority or some attribute to compare the object with and it throws the ClassCastException when it does not knows which attribute it should compare the object with.

Refer: https://www.sourcecodeexamples.net/2019/06/java-priority-queue-of-user-defined.html

Kindly upvote the solution, if it is helpful. Thank You.

Upvotes: 1

Related Questions