A priority-queue is an “abstract data type”. It is similar to a normal queue, but certain elements take priority when they are polled (perhaps for a print statement).

Why do we need priority queues?

Let’s say you’re in the hospital with a sore-throat at midnight. You have waited your turn, and now you are the front of the queue that the  emergency staff need to see. There are 5 people behind you with broken bones and 3rd degree burns. This is ultimately where the queue fails in real-life situations.

Namely because someone is likely to pass-away during the time it takes the nurses to source a throat lozenge and a paracetamol for you.

Priority queues allow you prioritise certain elements. Which is great for the people bleeding-out profusely, but not so great for your sore throat.

How Do You Create A Priority Queue In Java?

//This creates an empty Priority Queue with the default 11 element capacity.
PriorityQueue exampleQueue = new PriorityQueue();

//This creates a queue with capacity for 5 elements.
PriorityQueue fiveElementQueue = new PriorityQueue(5);

Simple Priority Queue Methods

How to add an Object to a Priority Queue

//First create some objects..
String feeling = “sad”;
String not = “popular”;

//Add the objects to it

How to return the front of Priority Queue

//This will return the front of the queue without dequeuing (removing) the element.

How return your Priority Queue as an Array

//This will return the front of the queue without dequeuing (removing) the element.

How to return the head (the ordered first in the queue; poll)

//This will dequeue and return the front of the queue based on priority.

Leave a Reply
You May Also Like

Java Classes: How to Make A New Class in Java

Classes are super important in Java and most other Object-orientated programing languages.…

Make Money Reselling Likes, Views & Subscribers

Social media panels are dashboards that allow you purchase a bunch of…