Does the PriorityQueue class inserts the elements priority wise or it's just that when we poll the element only then it finds out the highest priority element and returns it?
From the source code of JDK itself(formatting mine):
The Priority queue represented as a balanced binary heap: the two children of queue[n]
are queue[2*n+1]
and queue[2*(n+1)]
.
The priority queue is ordered by the comparator
, or by the elements' natural ordering, if the comparator is null: For each node n
in the heap and each descendant d
of n
, n <= d
. The element with the lowest value is in queue[0]
, assuming the queue is non-empty.
So, you can consider the insertion/deletion of elements in PriorityQueue as operations providing results along with the balancing of the heap.