2014-09-19 24 views
0

這是代碼和輸出低於它爲什麼值「5」和「6」我的意思是如何在PriorityQueue中的輪詢方法(類似於隊列中的其他元素)之後設置新的優先級。我正準備參加java認證考試,由於這個概念我總是傾向於選擇錯誤的答案,歡迎任何幫助。爲什麼在Java中的poll方法之後,PriorityQueue中的值會發生變化?

import java.util.*; 

public class PriorityQueueDemo { 
public static void main(String args[]) { 
    // create priority queue 
    PriorityQueue <Integer> prq = new PriorityQueue <Integer>(); 

    // insert values in the queue 
    for (int i = 3; i < 10; i++){ 
    prq.add (new Integer (i)) ; 
    } 

    System.out.println ("Initial priority queue values are: "+ prq); 

    // get the head from the queue 
    Integer head = prq.poll(); 

    System.out.println ("Head of the queue is: "+ head); 

    System.out.println ("Priority queue values after poll: "+ prq); 
} 
} 

輸出:

Initial priority queue values are: [3, 4, 5, 6, 7, 8, 9] 
Head of the queue is: 3 
Priority queue values after poll: [4, 6, 5, 9, 7, 8] 
+0

很難說了一些有趣的問題,而不會看到其他可能的答案。未指定打印元素的順序。但是,您可以根據元素數量和顯示的值得出結論。 – Thilo 2014-09-19 05:46:50

回答

2

值沒有改變,它們只是以不同的順序打印。
toString()對於PriorityQueue以它們的Iterator返回的順序返回元素。如果你讀的Javadoc PriorityQueue#iterator()你看到以下內容:

返回在此隊列中的元素的迭代器。迭代器不會以任何特定順序返回元素。

所以,你不能從您的打印得出任何結論,因爲沒有努力正在被PriorityQueue對打印他們在任何特定的順序,按優先級或以其他方式。

2

the docspoll()

獲取並移除此隊列的頭部,或返回null如果這個隊列是空的。

如果你想peek at the head而不刪除,請撥打peek()

獲取,但不移除此隊列的頭,如果此隊列爲空,則返回null。

訂購:優先級隊列實現高性能[O(日誌(n))的時間和入隊dequeing,恆定時間檢索]通過不排序的所有元素。它只是做一個部分排序來獲取頭部位置的最小元素。所以當繼承的AbstractCollection#toString()方法遍歷元素時,只有第一個按排序順序。當你刪除head元素時,會發生更多的排序,其他元素會改變相對位置。

請參閱維基百科以瞭解priority queues的工作原理。

1

對於考試記住的PriorityQueue隨時在正確的順序中的條目的第一條目和其他的可以爲任何順序,因爲

迭代器在方法迭代器(提供)不能保證 橫動元件以任何特定順序排列優先級隊列。

這一招救了我的時間來回答有關考試

+0

+1。但是它在toString()的哪個位置指定了哪個位置,即使第一個條目以正確的順序打印? Javadoc似乎只是說「不能以任何特定順序保證」。如果是這樣,他們怎麼能在考試中提出這個問題? (當然,根據其他答案的選擇,可能還有其他線索)。 – Thilo 2014-09-19 05:45:48

相關問題