按顺序遍历对象队列

2022-01-21 00:00:00 queue object java

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

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 Queue 状态:

队列通常(但不一定)以 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.

相关文章