I am implementing a PriorityQueue in my program. For that I have also implemented compareTo(). The compareTo() is being called when I perform add(), which is expected. But it is also called when I perform poll().
I thought that the function of poll() is just to remove the head. Why does it need to call compareTo()?
I am implementing a PriorityQueue in my program. For that I have also implemented
Share
The way a priority queue is implemented is often done with a heap. Part of
poll()ingrequires restructuring the heap which requires the heap to compare elements… hencecompareTo(). This is just a guess though (i.e. I have not dug into the source code to verify my claim).Here’s a quick search on how priority queues are implemented using heaps if you are interested: http://pages.cs.wisc.edu/~vernon/cs367/notes/11.PRIORITY-Q.html#imp
Actually just for fun I’ll describe how this works in a non-rigorous fashion. A heap is a tree satisfying the heap property: parents are always less than or equal to their children (min heap) or parents are always at least as large as their children (max heap).
PriorityQueueis a minheap sopoll()removes the root (make sure you understand this). But what happens to the tree if you remove the root? It’s no longer a tree… So the way they fix this is by moving the root of the tree to a leaf node (where it can be plucked without destroying the tree/invalidating the heap property), and putting some other node in the root. But which node do you put into the root? Intuitively you might think they’d put the left or right child of the root (those are “almost as small as the original root”). You can do that, but you’d then need to fix the subtree rooted at that child (and the code is ugly). Instead they do the same thing (conceptually) but do it slightly differently to make the code nicer. In particular, they pluck a leaf node and stick it in the root (generally you swap the root and the leaf node to do both steps simultaneously). However, the heap property is no longer necessarily satisfied (the leaf node we stuck in the root could be quite large!). To fix this, you “bubble down” the new root until you get it to its correct location. Specifically, you compare the new root with the left and right children and keep swapping (if the parent is larger than at least one of the children) until the heap property is satisfied. Notice that this swapping will indeed lead to a valid heap (you can prove this, but it’s intuitive).