Actually internal data structure of PriorityQueue
is not ordered, it is a heap.
PriorityQueue
doesn’t need to be ordered, instead, it focuses on head of data. Insertion is in O(log n) time. Sorting wastes time and useless for a queue.
Moreover, either the element is-a Comparable
, or a Comparator
is provided. Unfortunately, non-comparable checking is at runtime, rather than compile time. Once second element is added, ClassCastException
occurs.
PLUS: My answer to why [1, 3, 2, 4] instead of prints [1, 2, 3, 4]?
As I mentioned before, it’s not ordered, instead it focuses on head q[0]
is minimum, that’s it.
You could see the [1, 3, 2, 4] as a tree which is NOT linear:
1
| \
3 2
|
4