Suppose I use the PriorityQueue class from Java.util. I want to remove the largest number from the PriorityQueue pq, which we assume is at the head of the queue.
Will the following work?
// 1 int head = pq.peek(); pq.dequeue(head); // 2 int head = pq.dequeue(pq.peek());
Will this work the same for non-primitives?
Queue#peek and Queue#element return the initial value of the queue, Queue#poll and Queue#remove return and delete it.
Queue#peek
Queue#element
Queue#poll
Queue#remove
Similar to
int head = pq.poll();
- Is this what you want.
And: it will only work for non-primitive values, because the queue will only store objects. The trick is that (I think) your turn stores Integer values, and Java 1.5+ can automatically convert the results to int outboxing. Therefore, it feels that the int values ββare in the queue.
Integer
int
peek() - returns, but does not delete the value of the head
peek()
poll() - return and delete head value
poll()
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); pq.add(2);pq.add(3); System.out.println(pq); // [2, 3] System.out.println(pq.peek()); // head 2 System.out.println(pq); // 2 still exists. [2, 3] System.out.println(pq.poll()); // 2. remove head (2) System.out.println(pq); // [3]
Source: https://habr.com/ru/post/1332736/More articles:Interactive filter for media player (Youtube video game) - javaHow can I deal with 32-bit / 64-bit inconsistencies when doing IPC through SendMessage? - c ++Insert Last Name Contacts using Intreat android - androidWhat is the difference between os.popen and subprocess.Popen? - pythonHow to get data from json-rpc web service: iPad / iPhone / Objective-C - objective-cPoll images through javascript - javascriptSQL filtering across multiple columns - sqlGet sizes after setLayoutParams in Android - androidHow to host a web service in MVC3? - web-servicesarray: store multiple values ββper key - arraysAll Articles