Java 中无法在基于链表的队列中添加项目
Unable add item in a linkedList based Queue in Java
我正在使用 Queue 和 LinkedList。因此,我按照一些教程和 运行 创建了一个基于 LinkedList 的队列,并创建了一个从 0 - 9 遍历以添加到这些数字的循环。但是,完成后我发现文件开头有 10 个零,而不仅仅是 1。我从头部轮询了 1 个零并再次打印,但现在,我有 10 个或更多的 1,而不是少了一个零( 0).
这是我第一次使用队列,所以可能会有一些错误!
我的代码如下:
import java.util.LinkedList;
import java.util.Queue;
Queue<Integer> queue = new LinkedList<Integer>();
for(int i = 0; i < 10; i++)
{
System.out.println(i);
queue.add(i);
}
for(int i = 0; i < 10; i++)
{
System.out.print(queue.peek() + " >> ");
}
System.out.println();
System.out.println(queue.poll());
for(int i = 0; i < 10; i++)
{
System.out.print(queue.peek() + " $$ ");
}
System.out.println();
}}
这是我得到的输出集
0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >>
0
1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$
据我所知,第一行应该有 0 >> 1 >> 2 >> 3.... 而不是只有零 (0)。并且后续的最后一行也不应该只有 1。 我卡在这里了
你的代码实际上没问题。阅读 Java documentation on Queues,您会注意到 peek()
Retrieves, but does not remove, the head of this queue, or returns
null if this queue is empty.
多次调用 peek 不会更改您的队列。但是,如果你想删除元素,你可以使用 poll()
这将
Retrieve and remove the head of this queue, or return null if this
queue is empty.
得到零的原因是你的 queue-pointer 指向头部。您需要一个迭代器来遍历队列中的所有项目。
Iterator<Integer> iterator = queue.iterator();
while (iterator.hasNext()){
System.out.println((Integer)iterator.next);
}
我正在使用 Queue 和 LinkedList。因此,我按照一些教程和 运行 创建了一个基于 LinkedList 的队列,并创建了一个从 0 - 9 遍历以添加到这些数字的循环。但是,完成后我发现文件开头有 10 个零,而不仅仅是 1。我从头部轮询了 1 个零并再次打印,但现在,我有 10 个或更多的 1,而不是少了一个零( 0). 这是我第一次使用队列,所以可能会有一些错误! 我的代码如下:
import java.util.LinkedList;
import java.util.Queue;
Queue<Integer> queue = new LinkedList<Integer>();
for(int i = 0; i < 10; i++)
{
System.out.println(i);
queue.add(i);
}
for(int i = 0; i < 10; i++)
{
System.out.print(queue.peek() + " >> ");
}
System.out.println();
System.out.println(queue.poll());
for(int i = 0; i < 10; i++)
{
System.out.print(queue.peek() + " $$ ");
}
System.out.println();
}}
这是我得到的输出集
0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >>
0
1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$
据我所知,第一行应该有 0 >> 1 >> 2 >> 3.... 而不是只有零 (0)。并且后续的最后一行也不应该只有 1。 我卡在这里了
你的代码实际上没问题。阅读 Java documentation on Queues,您会注意到 peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
多次调用 peek 不会更改您的队列。但是,如果你想删除元素,你可以使用 poll()
这将
Retrieve and remove the head of this queue, or return null if this queue is empty.
得到零的原因是你的 queue-pointer 指向头部。您需要一个迭代器来遍历队列中的所有项目。
Iterator<Integer> iterator = queue.iterator();
while (iterator.hasNext()){
System.out.println((Integer)iterator.next);
}