0

I came across this example https://compiler.javatpoint.com/opr/test.jsp?filename=JavaPriorityQueueComparatorExample2 Here to my surprise priority queue is printing them in order of Ram got 98 marks. Rahul got 19 marks. Himanshu got 78 marks. Geetanjali got 18 marks.

Instead of Ram got 98 marks. Himanshu got 78 marks. Rahul got 19 marks. Geetanjali got 18 marks.

I ran this in eclipse and I noticed something interesting which I don't know why that is happening but when himanshu was getting added to the priority queue, it comparator checked it against Ram and not Rahul why? How I think a priority Queue works is that if a is greater than b then return -1 to show that b priority is lower than a. I would appreciate if someone could explain this.

CS Learner
  • 21
  • 4
  • 1
    PriorityQueue does not store elements in priority order, nor does its iterator iterate through elements in priority order. Rather the head of the queue is obtained in priority order. – Hovercraft Full Of Eels Apr 17 '22 at 18:28
  • 1
    Also, in the future, please post all code in the question and not in a link. – Hovercraft Full Of Eels Apr 17 '22 at 18:29
  • 1
    To underline @HovercraftFullOfEels's point here is an extract from [`PriorityQueue::iterator`'s documentation](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/PriorityQueue.html#iterator()): "*... The iterator does not return the elements in any particular order.*" – Turing85 Apr 17 '22 at 18:31

0 Answers0