

The front of the priority queue contains the least element according to the specified ordering, and the rear of the priority queue contains the greatest element. PriorityQueue queue = new PriorityQueue(Obj.Java Priority Queue Tutorial with Examples Rajeev Singh Java 2 mins readĪ priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation. How do you pass the object to compare and the argument to compare to the priority QueueĬomparator comparator = new NumberComparator() Still problem with the priority queue.Compilation error The PQ calls compareTo() and uses the results to decide which object to put in front of which.

You don't call compareTo(), and you don't do the swap. So, if you want your objects to be ordered correctly for a PriorityQueue, then you have to write a compareTo() method that looks at the priority of this and the priority of the object passed in, and deicdes which one is "less". So if I call pareTo(yourClassObject2), your compareTo method will return negative, zero, or positive, telling me that obj1 is less than, equal to, or greater than obj2, which I can then use decide whether to leave them as they are or swap them. The idea behind Comparable is that it's a way for other classes-classes that put things in order based on "less", "equal", or "greater"-to find out which of two objects of your class is "less than", "equal to", or "greater than" the other. It's not really clear what you're asking here. If I want to put this priority queue in order,I have to use comparable to point what argument to compare,and then what I'm only expecting you to show some effort and communicate the details of your problem. I'm definitely not expecting you to know everything. For instance, if I tell you, "You can't cast a Date to a List," do you know what that means? If not, what part don't you get? I was trying to get you to explain what part of it you (on the other side, trying to learn Java) didn't understand. The error message "X cannot be cast to Y" doesn't have a lot of complexity. What I was trying to get you do to was tell us what you read, and what part of it you didn't understand. But sometimes is confusing!!!And then I am asking for help. Of course first I am googling ,and try to read the docs. Maybe from the position of person knowing Java,it is hard for you to be on the other side(person tring to learn Java)
