Java 简明教程

Java PriorityQueue Class

Introduction

Java PriorityQueue 类是一个基于优先级堆的非有界优先级队列。以下是有关 PriorityQueue 的重要事项:

The Java PriorityQueue class is an unbounded priority queue based on a priority heap. Following are the important points about PriorityQueue −

  1. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

  2. A priority queue does not permit null elements.

  3. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects.

Class declaration

以下是*java.util.PriorityQueue* 类的声明 −

Following is the declaration for java.util.PriorityQueue class −

public class PriorityQueue<E>
   extends AbstractQueue<E>
   implements Serializable

Parameters

以下是*java.util.PriorityQueue* 类的参数 −

Following is the parameter for java.util.PriorityQueue class −

E − 这是此集合中保留元素的类型。

E − This is the type of elements held in this collection.

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.AbstractQueue

  2. java.util.AbstractCollection

  3. java.util.Object

  4. java.util.Collection

Adding an Item to a Priority Queue Example

以下示例展示了 Java PriorityQueue add(E) 方法的用法来添加 Integers。我们使用 add() 方法调用按元素为 PriorityQueue 对象添加一些 Integers,然后打印每个元素以显示添加的元素。

The following example shows the usage of Java PriorityQueue add(E) method to add Integers. We’re adding couple of Integers to the PriorityQueue object using add() method calls per element and then print each element to show the elements added.

package com.tutorialspoint;

import java.util.PriorityQueue;

public class PriorityQueueDemo {
   public static void main(String[] args) {

      // create an empty priority queue with an initial capacity
      PriorityQueue<Integer> queue = new PriorityQueue<>(5);

      // use add() method to add elements in the queue
      queue.add(20);
      queue.add(30);
      queue.add(20);
      queue.add(30);
      queue.add(15);
      queue.add(22);
      queue.add(11);

      // let us print all the elements available in queue
      for (Integer number : queue) {
         System.out.println("Number = " + number);
      }
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Number = 11
Number = 20
Number = 15
Number = 30
Number = 30
Number = 22
Number = 20