1

在下面的代码中,我想在创建 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() + " ");
    }
}
4

2 回答 2

1

Javadoc解释:

优先级队列是无界的,但具有控制用于存储队列元素的数组大小的内部容量。它总是至少与队列大小一样大。随着元素被添加到优先级队列中,其容量会自动增长。增长政策的细节没有具体说明。

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

于 2012-05-23T07:37:27.757 回答
0

API 文档确实解释了容量是什么。它是内部数组的大小。

http://download.java.net/jdk7/archive/b123/docs/api/java/util/PriorityQueue.html

Allowing you to specify an initial capacity is a small optimization. 
If you know how many entries you will need, you can save the (tiny) time 
spent growing the queue to the required size, by sizing it correctly 
from the start.
于 2012-05-23T07:40:53.293 回答