2012-05-23 36 views
1

在下面的代碼中,我想知道在創建PrioriyQueue時的意義。我知道它的初始容量,但會影響性能嗎?Java中的PriorityQueue說明

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() + " "); 
    } 
} 
+0

你考慮閱讀的Javadoc您發佈過嗎?而不是發佈? – EJP

回答

1

Javadoc說明:

優先級隊列是無界的,但具有管理用於存儲隊列中的元素的數組的大小的內部容量。它總是至少與隊列大小一樣大。隨着元素被添加到優先級隊列中,其容量會自動增加。增長政策的細節沒有說明。

換句話說,如果發現隊列花費太多時間來增長內部陣列,能夠指定初始容量是一種優化性能的方法。

+0

你可能對ArrayList(和其他一些集合)有同樣的問題:http://stackoverflow.com/questions/3564837/capacity-of-arraylist –