In: Computer Science
As the following statements execute, what is the content of the priority queue? Show the content of the queue after each step:
PriorityQueue<String> myPriorityQueue = new PriorityQueue<>(); myPriorityQueue.offer("Jim"); myPriorityQueue.offer ("Jess"); myPriorityQueue.offer ("Jill"); myPriorityQueue.offer ("Jane"); String name = myPriorityQueue.poll(); myPriorityQueue.offer (name); myPriorityQueue.offer (myPriorityQueue.peek()); myPriorityQueue.offer ("Jim"); myPriorityQueue.poll();
Here, offer() is just like an add operation to the Priority queue.(By default adds in ascending order) peek() will just return the head from the Priority queue. poll() will return the head and removed from the Priority queue. i.) PriorityQueue<String> myPriorityQueue = new PriorityQueue<>();
Here myPriorityQueue will be created
ii.) myPriorityQueue.offer("Jim");
Jim will be added to myPriorityQueue.
myPriorityQueue=["Jim"]
iii.) myPriorityQueue.offer ("Jess");
Jess will be added to myPriorityQueue.
myPriorityQueue=["Jess","Jim"]
iv.) myPriorityQueue.offer ("Jill");
Jill will be added to myPriorityQueue.
myPriorityQueue=["Jess","Jill","Jim"]
v.) myPriorityQueue.offer ("Jane");
Jane will be added to myPriorityQueue.
myPriorityQueue=["Jane","Jess","Jill","Jim"]
vi.) String name = myPriorityQueue.poll();
The head of myPriorityQueue will be returned and removed from it. So here, Jane will be returned and removed from the queue.
name="Jane"
myPriorityQueue=["Jess","Jill","Jim"]
vii.) myPriorityQueue.offer (name);
Here name="Jane"
Jane will be added to myPriorityQueue.
myPriorityQueue=["Jane","Jess","Jill","Jim"]
viii.) myPriorityQueue.offer (myPriorityQueue.peek());
peek() will just return the head
myPriorityQueue.peek() wil give us "Jane"
myPriorityQueue.offer (myPriorityQueue.peek()) will add "Jane" to the queue
myPriorityQueue=["Jane","Jane","Jess","Jill","Jim"]
ix.)myPriorityQueue.offer ("Jim");
Jim will be added to myPriorityQueue.
myPriorityQueue=["Jane","Jane","Jess","Jill","Jim","Jim"]
x.) myPriorityQueue.poll();
The head will be returned and removed from the queue. So, "Jane" will be returned and removed from the queue
myPriorityQueue=["Jane","Jess","Jill","Jim","Jim"]
So, after executing the above operations myPriorityQueue=["Jane","Jess","Jill","Jim","Jim"]
#Please don't forget to upvote if you find the solution helpful.
Feel free to ask doubts if any, in the comments section. Thank
you.