📅  最后修改于: 2023-12-03 15:15:57.493000             🧑  作者: Mango
Java PriorityQueue is a class in the Java Collections Framework that implements the Queue interface. It represents an unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering or by their comparator.
PriorityQueue<Integer> pq = new PriorityQueue<>();
This creates a new priority queue of integers with the default initial capacity (11) and natural ordering.
PriorityQueue<String> pq = new PriorityQueue<>(Collections.reverseOrder());
This creates a new priority queue of strings with the reverse ordering.
pq.add(5);
pq.add(2);
pq.add(7);
int highestPriority = pq.poll();
// highestPriority is 2
Elements can be added to the priority queue using the add()
method. The poll()
method removes the element with the highest priority.
PriorityQueue<String> pq = new PriorityQueue<>(Comparator.comparing(String::length));
pq.add("hello");
pq.add("world");
pq.add("java");
String shortestString = pq.peek();
// shortestString is "java"
Custom ordering can be achieved by passing a Comparator
object to the PriorityQueue constructor.
PriorityQueue<Integer> pq = new PriorityQueue<>(Arrays.asList(1, 2, 3, 4, 5));
pq.remove(3);
pq.add(6);
int highestPriority = pq.poll();
// highestPriority is 1
The priority of an element in the queue can be modified by removing it and adding it back with a new value.
Java PriorityQueue is a useful class for implementing priority queue functionality in Java applications. It provides a simple way to add, remove, and modify elements based on their priority.