Collections Flashcards
PriorityQueue
It is an implementation of minheap by default.
A binary heap which ensures the item with highest priority is always at the top or index 0 for an array implementation of the heap.
When you do a get from a priorityqueue by default you will get the smallest element ie minheap
you can change that by
new PriorityQueye(Collections.reverseOder)
here you are providing a standard comparator from the Collections class
you can choose to provide custom comparators also
or make your custom class which are being stored in the queue to implement Comparable interface which has the compareto method.
PriorityQueue is an unbounded queue
The default initial capacity is ‘11’ which can be overridden using initialCapacity parameter
operations poll, remove, peek, : top element
PriorityQueue is not thread-safe. Use PriorityBlockingQueue in a concurrent environment.
provides O(log(n)) time performance for add and poll
where is priorityqueue used
Task Scheduling: When scheduling tasks based on their priority, a PriorityQueue can be helpful to determine the next task with the highest priority efficiently.
A* Search Algorithm: It is a popular pathfinding algorithm used in various applications, such as route planning and game development. PriorityQueue can prioritize nodes based on their total estimated cost from the start to the goal.
Dijkstra’s Algorithm: It finds the shortest path in a graph from a single source to all other nodes. A PriorityQueue efficiently selects the next node with the shortest distance during the algorithm’s execution.