在下面的代码中,我想知道创建 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/