我如何在Java中修改PriorityQueue的元素?

我如何在Java中修改PriorityQueue的元素?

通常,队列遵循先进先出(FIFO)的原则,但是PriorityQueue 按照优先级的方式访问元素时,遵循一种基于优先级的方法。队列的每个元素 具有与之关联的优先级。元素根据自然排序进行优先排序 order. However, we can provide custom orders using a comparator. The elements of PriorityQueue are not actually sorted, they are only retrieved in sorted order. This feature allows us to modify an element of PriorityQueue easily.

Java Program to modify an element of a ProrityQueue

在开始程序之前,让我们先了解一下PriorityQueue的几个内置方法 -

  • add() − It is used to add a single element to the queue

  • offer() − 它还将给定的元素插入到队列中。

  • peek() − 用于检索队列的第一个元素。

  • remove() − It is used to remove the specified element from the queue.

Approach 1

  • 定义一个PriorityQueue集合的对象,并使用'add()'方法存储一些元素

  • method.
  • Now, using ‘peek()’ method show the first element of queue and then remove this 使用 'remove()' 方法从队列中移除元素

  • 进一步移动,使用内置方法在相同位置插入一个新元素

  • ‘offer()’.
  • Again show the modified first element.

Example

In the following example, we will modify an element of PriorityQueue. The elements are

没有比较器的优先级,这意味着它们将按升序访问。

import java.util.*; public class Modify { public static void main(String[] args) { PriorityQueue queuePq = new PriorityQueue(); // inserting elements queuePq.add(7); queuePq.add(9); queuePq.add(2); queuePq.add(4); queuePq.add(3); System.out.println("Original Queue: " + queuePq); int head1 = queuePq.peek(); // accessing first element System.out.println("The first element in Queue: " + head1); queuePq.remove(2); // removing first element queuePq.offer(1); // adding new element at first position int head2 = queuePq.peek(); // accessing first element System.out.println("The updated first element in Queue: " + head2); queuePq.offer(2); // adding new element at first position System.out.println("Newly updated Queue: " + queuePq); } } 登录后复制