Priority queue ordering of elements

后端 未结 4 429
情话喂你
情话喂你 2020-12-18 00:31

How come the elements of priority queue are ordered according to natural order by default as it doesn\'t implement comparable interface.

From the docs, it says elem

4条回答
  •  时光取名叫无心
    2020-12-18 01:20

    You are seeing that order because:

    1. Internally System.out.println() will be invoking the toString() method which in turn uses the iterator to iterate through the elements of the queue. But the iterator does not guarantee any specific order to traverse the elements. Refer this

    http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html


    2. Priority queue is based on priority heap. When an element is inserted without any comparator then priority queue uses siftUpComparable() method internally. siftUpComparable() compares the current element with the element at it's parent position in the heap. If the order is not correct then current element and parent element are swapped. This is done until the current element and parent element are in correct order. Ordering is based on natural order of the element.

    3. Since priority queue is based on priority heap its main focus will be on element in front of the queue. So the elements are ordered when an element is dequeued from the queue using poll(). This is done to increase the performance of Priority queue. Priority queue only orders the elements when it requires.
    If you want to see the order as [1, 2, 3, 4] then use this

    while(pq.size() != 0) { 
        System.out.println(pq.poll());
    }
    

提交回复
热议问题