📜  Java PriorityQueue(1)

📅  最后修改于: 2023-12-03 15:15:57.493000             🧑  作者: Mango

Java PriorityQueue

Introduction

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.

Features
  • Implements the Queue interface, which provides the standard queue operations: add, poll, peek, etc.
  • Doesn't allow null elements.
  • Allows elements to be added in any order and removes them based on their priority.
  • Provides methods to modify the priority of an element in the queue.
  • Uses a binary heap data structure to store elements.
  • Provides faster retrieval of highest-priority element than other queue implementations.
Usage
Creating a PriorityQueue
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.

Add and Remove Elements
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.

Custom Ordering
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.

Modifying Element Priority
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.

Conclusion

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.