2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I have updated the question with my output set. See, instead of 0, 1 , 2, 3... I only have 0 and when I polled it out, I have 1, 1, 1, 1....
Yes, because you poll once and peek a hundred times, which results in one change in the queue and a hundred calls without any change. If you want to see all items of the queue, you will have to use poll every time (which will also emtpy the queue, but that's the way how queues work).
oh! thanks man! it really worked :).. I did not know. I get it now, peek is just giving me the first item of the Queue... right :) Thanks again mate
1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.