按顺序迭代对象队列 [英] Iterate through Queue of Objects in Order

查看:111
本文介绍了按顺序迭代对象队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含对象的队列,我希望按照它们放入队列的顺序进行迭代(第一个对象放在队列中,第二个对象放在队列中,第三个对象......)

I have created a queue containing objects which I would like to iterate through in the order that they were placed within the queue (First object placed in queue, 2nd object placed in queue, 3rd object...)

我看到了一种在线方式,但我不确定这是否能保证队列中的对象能够以正确的顺序访问?

I saw a way of doing this online but I'm not sure if this will guarantee that objects in the queue will be visited in the correct order?

for(MyObject anObject : queue){
    //do someting to anObject...

感谢您的帮助。

推荐答案

这取决于您使用的 Queue 实现。

It depends on which Queue implementation you use.

例如 LinkedList 保证迭代将以FIFO(插入)顺序返回元素。这是因为它实现了 Deque 界面

For example LinkedList guarantees that iterations will return elements in FIFO (insertion) order. This is because it implements the Deque interface.

但一般来说,其他类型的队列并不一定如此。

But generally speaking it is not necessarily the case for other types of Queues.

javadoc for队列指出:


队列通常(但不一定)在FIFO中排序元素(先进先出)方式。其中的例外是优先级队列,它根据提供的比较器对元素进行排序,或者元素的自然排序,以及LIFO队列(或堆栈),它们对元素LIFO(后进先出)进行排序。

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out).

它还添加:


每个队列实现必须指定其订购属性。

Every Queue implementation must specify its ordering properties.

所以你只需要检查你正在使用的特定队列的javadoc,你应该找到你的答案。

So you simply need to check the javadoc of the specific queue you are using and you should find your answer.

这篇关于按顺序迭代对象队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆