2015-03-03 62 views
1

我有一個對象隊列,我想穿過隊列並能夠使用這些對象。Java瀏覽對象隊列

我有這樣的:

private String format(Queue<MyObject> queue) { 

    for (int i = 0; i < queue.size(); i++) { 
     //Here i would like to use "MyObject" 
    } 

} 

我不知道如果我錯了,但我無法找到一個好辦法做到這一點。 感謝您的幫助,

+0

您的意思是瀏覽隊列而不實際刪除任何元素? – Eran 2015-03-03 09:13:04

+0

是的,我想使用隊列中的所有數據,格式化並返回。 – YanZaX 2015-03-03 09:16:52

回答

0

那麼,根據實際的隊列實現,您可能可以使用迭代器。

例如,對於PriorityQueue<E>

* <p>This class and its iterator implement all of the 
* <em>optional</em> methods of the {@link Collection} and {@link 
* Iterator} interfaces. The Iterator provided in method {@link 
* #iterator()} is <em>not</em> guaranteed to traverse the elements of 
* the priority queue in any particular order. If you need ordered 
* traversal, consider using {@code Arrays.sort(pq.toArray())}. 

這意味着,增強的for循環將工作:

for (MyObject obj : queue) { 

} 

不過,並不是每個Queue實現是保證實現iterator()。您應該檢查您使用的實際Queue實現是否支持迭代。

+0

這工作,thx很多。 – YanZaX 2015-03-03 10:06:48

0

你可以保持enqueue()dequeue()元素從隊列中,如果你在每次迭代做他們兩人恰好一次,可以保證隊列的大小不會改變,而當你做 - 隊列將保持原樣。

0

你可以用的元素列表:

List<MyObject> list = new ArrayList<>(queue); 

並重複列表。