Java浏览对象队列
我有一个对象队列,我想遍历队列并能够使用这些对象 我有这个:Java浏览对象队列,java,queue,Java,Queue,我有一个对象队列,我想遍历队列并能够使用这些对象 我有这个: private String format(Queue<MyObject> queue) { for (int i = 0; i < queue.size(); i++) { //Here i would like to use "MyObject" } } 专用字符串格式(队列){ 对于(int i=0;i
private String format(Queue<MyObject> queue) {
for (int i = 0; i < queue.size(); i++) {
//Here i would like to use "MyObject"
}
}
专用字符串格式(队列){
对于(int i=0;i
我不知道我是否错了,但我找不到一个好办法来做。
感谢您的帮助,您可以保留队列中的
enqueue()
和dequeue()
元素,如果您在每次迭代中同时执行这两个元素,则可以保证队列的大小不会改变,完成后,队列将保持原来的状态。您可以将元素包装在列表中:
List<MyObject> list = new ArrayList<>(queue);
List List=newarraylist(队列);
然后迭代列表。根据实际的队列实现,您可以使用迭代器 例如,对于
PriorityQueue
:
但是,并不是每个队列实现都保证实现
iterator()
。您应该检查您正在使用的实际队列实现是否支持迭代。您的意思是浏览队列而不实际删除任何元素吗?是的,我想使用队列中的所有数据,格式化它,然后返回它。
* <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 (MyObject obj : queue) {
}