2015-03-03 47 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); 

并重复列表。