[英]How can I print all the elements in a Generic Linked List Queue?
This is the current method I'm working with.这是我正在使用的当前方法。 newt
is the name of the Generic LinkedList
Queue
. newt
是通用LinkedList
Queue
的名称。
newt.peek()
returns the data inside of the head of the queue . newt.peek()
返回队列头部的数据。
I'm not sure how to go through each element in the queue (this is my first time working with a queue) and print the data in each one.我不确定如何通过队列中的每个元素 go (这是我第一次使用队列)并打印每个元素中的数据。
//Print all elements of the queue.
public void printProcessQueue() {
boolean hasMore = true;
while (hasMore) {
if (newt.peek() != null) {
System.out.println(newt.head);
//Cannot figure out how to get the next in queue
}
}
}
how to go through each element in the queue and print the data in each one如何通过队列中的每个元素 go 并打印每个元素中的数据
You can do it by removing the head of the queue in a loop until the queue is not empty:您可以通过在循环中删除队列的头部直到队列不为空来做到这一点:
public void printQueue() {
while (!queue.isEmpty()) { // basically you can use `queue.peek() != null`, but `isEmpty()` is more preferable because it's more expressive
System.out.println(queue.remove()); // or queue.poll()
}
}
If you're not OK with removing all the elements from the queue , then you can make use of the iterator .如果您不同意从队列中删除所有元素,那么您可以使用迭代器。 But note that iterator created over the elements of the queue will not necessarily guarantee to traverse them in any specific order.但请注意,在队列元素上创建的迭代器不一定保证以任何特定顺序遍历它们。 It will depend on the implementation: for instance, ArrayDeque
and LinkedList
give you such guarantee, but PriorityQueue
doesn't.这将取决于实现:例如, ArrayDeque
和LinkedList
给你这样的保证,但PriorityQueue
没有。
public void printQueue() {
Iterator<MyType> iterator = queue.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
Sidenote: when you need a Queue
(or Deque
) favor ArrayDeque
over LinkedList
as a more performant implementation.旁注:当您需要Queue
(或Deque
)时, ArrayDeque
而不是LinkedList
作为性能更高的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.