Priority queue is a priority queue and also a heap we usually talk about. It can achieve O (1) to obtain the Maximum/minimum elements and maintain the operation time complexity O (logn)
For more information about common APIs, see priorityqueue:
| Constructor Summary |
PriorityQueue() Use the default initial capacity (11) to createPriorityQueueAnd sort the elements in the natural order. |
PriorityQueue(Collection<? extends E> c) CreatePriorityQueue. |
PriorityQueue(int initialCapacity) CreatesPriorityQueueAnd sort the elements in the natural order. |
PriorityQueue(int initialCapacity, Comparator<? super E> comparator) CreatesPriorityQueueAnd sort the elements according to the specified comparator. |
PriorityQueue(PriorityQueue<? extends E> c) Create a queue with the specified priorityPriorityQueue. |
PriorityQueue(SortedSet<? extends E> c) CreatePriorityQueue. |
| Method Summary |
boolean |
add(E e) Inserts the specified element into this priority queue. |
void |
clear() Removes all elements from this priority queue. |
Comparator<? super E> |
comparator() Returns the comparator used to sort the elements in the queue. If the queue sorts the elements in the natural order, the system returnsnull. |
boolean |
contains(Object o) If the queue contains the specified elementtrue. |
Iterator<E> |
iterator() Returns the iterator that iterates over the elements in this queue. |
boolean |
offer(E e) Inserts the specified element into this priority queue. |
E |
peek() Obtains but does not remove the header of this queue. If this queue is empty, returnNull. |
E |
poll() Gets and removes the queue header. If this queue is empty, the system returnsNull. |
boolean |
remove(Object o) Remove a single instance of the specified element from this queue (if any ). |
int |
size() Returns the number of elements in the collection. |
Object[] |
toArray() Returns an array containing all elements of this queue. |
|
toArray(T[] a) Returns an array containing all elements of the queue. The runtime type of the returned array is the type of the specified array. |
We often use the maximum or minimum heap during use. Priorityqueue is the minimum heap by default. To use the maximum heap, You need to override the Compare function of the comparator object. The example is as follows:
Comparator<Integer> cmp;cmp = new Comparator<Integer>() {public int compare(Integer e1, Integer e2) {return e2 - e1;}};Queue<Integer> q2 = new PriorityQueue<Integer>(5,cmp);