How does `PriorityQueue` maintain order?
PriorityQueue
maintains order by using a heap (typically a binary heap), which is a complete binary tree where each parent node is ordered relative to its children.
- Natural ordering: The elements are ordered based on their natural order (for comparable objects) or by a comparator provided at the time of creation.
- Heap property: For a min-heap (default), the smallest element is at the root, and for a max-heap, the largest element is at the root.
This structure ensures that the element with the highest priority is always accessible in constant time (O(1)
), and inserting or removing elements takes logarithmic time (O(log n)
).