Reputation:
I was working with Queue and LinkedList. So, I created a LinkedList based queue following some tutorial and ran a loop to traverse from 0 - 9 to add to those numbers. However, after finishing I found out that I have 10 zeros in the beginning of the file instead of just 1. I polled out 1 zero from the head and print it again but now, I have 10 or more 1, not one less zero (0). This is the first time I am working with queue, so there might be some mistakes! My code is given below:
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();
}}
This is the output set I am getting
0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >> 0 >>
0
1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$ 1 $$
In my knowledge, I should have 0 >> 1 >> 2 >> 3.... instead of only zeros (0) in the first line. and the follow up final line should not be only 1 as well. I am stuck here
Upvotes: 2
Views: 56
Reputation: 1774
The reason for getting zeros is that your queue-pointer is pointing to the head. You need a iterator to go through all the items in the queue.
Iterator<Integer> iterator = queue.iterator();
while (iterator.hasNext()){
System.out.println((Integer)iterator.next);
}
Upvotes: 1
Reputation: 1249
Your code is actually fine. Reading the Java documentation on Queues, you will notice that peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
Calling peek multiple times will not change your queue. However, if you want to remove the elements, you can use poll()
which will
Retrieve and remove the head of this queue, or return null if this queue is empty.
Upvotes: 1