java - Java 中的 PriorityQueue 说明

标签 java priority-queue

在下面的代码中,我想知道创建 PrioriyQueue 时 10 的意义。我知道它的初始容量,但它会影响性能吗?

import java.util.*;

class Test {
    static class PQsort implements Comparator<Integer> { // inverse sort
        public int compare(Integer one, Integer two) {
            return two - one; // unboxing
        }
    }

    public static void main(String[] args) {
        int[] ia = { 1, 5, 3, 7, 6, 9, 8 }; // unordered data
        PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(); // use
                                                                    // natural
                                                                    // order
        for (int x : ia)
            pq1.offer(x);
        for (int x : ia)
            // review queue
            System.out.print(pq1.poll() + " ");
        System.out.println("");
        PQsort pqs = new PQsort(); // get a Comparator
        PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs); // use
                                                                            // Comparator
        for (int x : ia)
            // load queue
            pq2.offer(x);
        System.out.println("size " + pq2.size());
        System.out.println("peek " + pq2.peek());
        System.out.println("size " + pq2.size());
        System.out.println("poll " + pq2.poll());
        System.out.println("size " + pq2.size());
        for (int x : ia)
            // review queue
            System.out.print(pq2.poll() + " ");
    }
}

最佳答案

Javadoc解释:

A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified.

换句话说,如果发现队列花费太多时间增长其内部数组,则能够指定初始容量是优化性能的一种方法。

关于java - Java 中的 PriorityQueue 说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10715428/

相关文章:

java - 尝试将对象添加到 PriorityQueue 时出现 NullPointerException

STL - 为什么pop_heap的复杂度是O(2 * log(N))?

java - 检查实体附有其标识符

java - Java 的 TTS(文本转语音)API 的最佳替代品是什么?

java - 有没有办法在 swingworker 完成之前阻塞主线程?

java - 解析时间戳后,它在 Java 中的时间戳中添加毫秒

Python:更新heapq中元素的值

c++ - 优先队列,重载少操作

java - 如果 Kafka 节点出现故障,则发出警报

c++ - 初始化指向类实例的智能指针并访问其方法