Iterate through Queue of Objects in Order(按顺序遍历对象队列)
问题描述
我创建了一个包含对象的队列,我想按照它们在队列中的放置顺序对其进行迭代(第一个对象放置在队列中,第二个对象放置在队列中,第三个对象......)
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.
这篇关于按顺序遍历对象队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按顺序遍历对象队列
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01