java 优先队列_优先队列Java

java 优先队列

Every now and then we need to process items of a queue in a particular order. Priority queue is a Data Structure that does the job. Java priority queue is different from “normal” queue. Instead of “First-In-First-Out”, it retrieves the items in order of their priority.

我们有时需要按特定顺序处理队列中的项目。 优先级队列是完成任务的数据结构。 Java优先级队列与“普通” 队列不同 。 代替“先进先出”,它按优先级顺序检索项目。

优先队列Java (Priority Queue Java)

The java.util.PriorityQueue class, provides us an implementation of such a data type, by using priority heap implementation internally. Java PriorityQueue is an unbounded queue. It was introduced in Java 1.5 and enhanced in Java SE 8 release. PriorityQueue is internally implemented by following “Priority Heap” data structure.

java.util.PriorityQueue类通过内部使用优先级堆实现为我们提供了这种数据类型的实现。 Java PriorityQueue是一个无界队列。 它是在Java 1.5中引入的,并在Java SE 8版本中得到了增强。 PriorityQueue通过遵循“ Priority Heap”数据结构在内部实现。

Here is the PriorityQueue class hierarchy:

这是PriorityQueue类层次结构:

PriorityQueue Class Diagram:

PriorityQueue类图:

Java PriorityQueue构造函数 (Java PriorityQueue Constructors)

  1. PriorityQueue() – Creates a PriorityQueue with the default initial capacity, i.e. 11

    PriorityQueue() –使用默认初始容量(即11 创建一个PriorityQueue
  2. PriorityQueue(Collection c) – Creates a PriorityQueue with the elements in the specified collection

    PriorityQueue(Collection c) –使用指定集合中的元素创建一个PriorityQueue
  3. PriorityQueue(int initialCapacity) – Creates a PriorityQueue with the specified initial capacity

    PriorityQueue(int initialCapacity) –创建具有指定初始容量的PriorityQueue
  4. PriorityQueue(int initialCapacity, Comparator comparator) – Creates a PriorityQueue with the provided initial capacity and the ordering of its elements is according to the specified comparator

    PriorityQueue(int initialCapacity,Comparator比较器) –创建具有提供的初始容量的PriorityQueue,其元素的顺序根据指定的比较器
  5. PriorityQueue(PriorityQueue c) – Creates a PriorityQueue containing the elements in the specified priority queue

    PriorityQueue(PriorityQueue c) –创建一个包含指定优先级队列中元素的PriorityQueue
  6. PriorityQueue(SortedSet c) – Creates a PriorityQueue containing the elements in the specified sorted set

    PriorityQueue(SortedSet c) –创建一个包含指定排序集中的元素的PriorityQueue

Priority Queue elements are ordered by their natural ordering unless we provide a Comparator while creating it.
The elements are ordered in ascending order by default, hence the head of the queue is the element whose priority is lowest.

除非我们在创建Comparator时提供它,否则Priority Queue元素将按照其自然顺序进行排序。
默认情况下,元素按升序排列,因此队列的开头是优先级最低的元素。

If there are two elements which are eligible to become the head at the same time, this kind of ties are broken arbitrarily.

如果有两个元素可以同时成为负责人,则这种联系会被任意打破。

Java PriorityQueue示例 (Java PriorityQueue Example)

Let’s create a PriorityQueue, containing various tasks:

让我们创建一个PriorityQueue ,其中包含各种任务:

PriorityQueue tasks=new PriorityQueue();
tasks.add("task1");
tasks.add("task4");
tasks.add("task3");
tasks.add("task2");
tasks.add("task5");

This creates a PriorityQueue of tasks, which will be ordered by the natural ordering of String.
Let’s create another PriorityQueue which orders the tasks in reverse order of natural ordering. So we need to pass a Comparator:

这将创建一个PriorityQueue任务,该任务将按String的自然顺序进行排序。
让我们创建另一个PriorityQueue,它以自然顺序的相反顺序对任务进行排序。 因此,我们需要通过一个比较器:

PriorityQueue reverseTasks=new PriorityQueue(Comparator.reverseOrder());
reverseTasks.add("task1");
reverseTasks.add("task4");
reverseTasks.add("task3");
reverseTasks.add("task2");
reverseTasks.add("task5");

Java PriorityQueue方法 (Java PriorityQueue Methods)

Now, let’s take a look at all the methods available for PriorityQueue and use them:

现在,让我们看一下PriorityQueue可用的所有方法并使用它们:

  1. Boolean add(E e) – This method inserts the specified element in the queue.
    We have already added 5 tasks in our queue using this method.

    布尔值add(E e) –此方法将指定的元素插入队列。
    我们已经使用这种方法在队列中添加了5个任务。
  2. Comparator comparator() – This method returns the Comparator used to order the elements in this queue. It returns null if no comparator was specified and the queue is sorted according to the natural ordering of its elements.
    So, if we do:
    System.out.println(tasks.comparator());
    System.out.println(reverseTasks.comparator());

    The output will be:

    比较器比较器() -此方法返回用于对队列中的元素进行排序的比较器 。 如果未指定比较器,并且队列根据其元素的自然顺序排序,则返回null。
    因此,如果我们这样做:
    System.out.println(tasks.comparator());
    System.out.println(reverseTasks.comparator());

    输出将是:

  3. boolean contains(Object o) – Returns true if the queue contains the specified element.
    Let’s check if “task3” belongs to the Priority queue tasks:
    System.out.println(tasks.contains("task3"));

    This prints:

    boolean contains(Object o) –如果队列包含指定的元素,则返回true。
    让我们检查“ task3”是否属于优先级队列任务:
    System.out.println(tasks.contains("task3"));

    打印:

  4. boolean offer(E e) – Just like the add() method, this method also adds an element to the queue.
    The offer() and add() methods are actually a bit different for capacity constrained queues, but in case of PriorityQueue, both are same. Unlike add(), offer() does not throw an exception even if it fails to add the element in the queue.

    boolean offer(E e) –就像add()方法一样,此方法也将元素添加到队列中。
    对于容量受限制的队列,offer()和add()方法实际上有些不同,但是对于PriorityQueue,两者是相同的。 与add()不同,即使offer()无法将元素添加到队列中,它也不会引发异常。
  5. E peek() – Retrieves the head of this queue, or returns null if this queue is empty. In other words, it returns the element with highest priority.
    So the following code:
    System.out.println(tasks.peek());
    System.out.println(reverseTasks.peek());

    Gives us:

    E peek() –检索此队列的开头,如果此队列为空,则返回null。 换句话说,它返回具有最高优先级的元素。
    所以下面的代码:
    System.out.println(tasks.peek());
    System.out.println(reverseTasks.peek());

    给我们:

  6. E poll() – This method also retrieves the head of the queue(element with highest priority), or returns null if the queue is empty. But unlike peek(), it also removes the element.
    So, if we call poll():
    System.out.println(“Poll on tasks: ”+tasks.poll());
    System.out.println(“Poll on reverseTasks: ”+reverseTasks.poll());

    And then peek:

    We’ll have the following outptut:

    Poll on tasks: task1
    Poll on reverseTasks: task5
    Peek on tasks: task2
    Peek on reverseTasks: task4

    E poll() –此方法还检索队列的头部(具有最高优先级的元素),如果队列为空,则返回null。 但是与peek()不同,它还删除了元素。
    因此,如果我们调用poll():

    然后偷看:

    System.out.println(“Peek on tasks: ”+tasks.peek());
    System.out.println(“Peek on reverseTasks: ”+reverseTasks.peek());

    我们将提供以下输出:

  7. int size() – Returns the number of elements in the queue.

    int size() –返回队列中元素的数量。
  8. boolean remove(Object o) – Removes the specified element from the queue, if it’s present. If two same elements are present, it only removes one of them.

    boolean remove(Object o) -从队列中删除指定的元素(如果存在)。 如果存在两个相同的元素,则仅删除其中之一。
  9. Object[] toArray() – Returns an array containing all the elements in the queue.

    Object [] toArray() –返回包含队列中所有元素的数组。
  10. T[] toArray(T[] a) – Returns an array containing all the elements in the queue, and the type of the returned array is that of the specified array.

    T [] toArray(T [] a) –返回包含队列中所有元素的数组,并且返回的数组的类型为指定数组的类型。
  11. Iterator iterator() – Returns an iterator for the queue.

    Iterator iterator() –返回队列的迭代器。
  12. void clear() – Removes all of the elements from the queue.

    void clear() –从队列中删除所有元素。

Apart from these, the PriorityQueue also inherits the methods from the Collection and Object classes.

除此之外, PriorityQueue还继承了CollectionObject类的方法。

Java PriorityQueue时间复杂度 (Java PriorityQueue Time Complexity)

  1. For enqueing and dequeing methods, the time complexity is O(log(n))

    对于入队和出队方法,时间复杂度为O(log(n))
  2. For the remove(Object) and contains(Object) methods, the time complexity is linear

    对于remove(Object)和contains(Object)方法,时间复杂度是线性的
  3. For the retrieval methods, it has constant time complexity

    对于检索方法,它具有恒定的时间复杂度

This implementation of priority queue is not thread-safe. So, if we need synchronised access, we need to use PriorityBlockingQueue.

优先级队列的此实现不是线程安全的。 因此,如果需要同步访问,则需要使用PriorityBlockingQueue 。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16254/priority-queue-java

java 优先队列

你可能感兴趣的:(队列,java,数据结构,queue,python)