Queue interface is in java.util package of java. Queue works like first in first out (FIFO) policy. Queue does not require any fix dimension like String array and int array. Queue contains many useful methods. To add element in Queue, we can use add() method of Queue interface.
To get value from Queue, Queue provides poll() and peek() method and Queue size() method. Size() method returns total number of elements in Queue. peek() method looks at the object at the head of this Queue without removing it from the Queue
Queue Example
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<String> qe=new LinkedList<String>(); qe.add("b"); qe.add("a"); qe.add("c"); qe.add("e"); qe.add("d"); Iterator it=qe.iterator(); System.out.println("Initial Size of Queue :"+qe.size()); while(it.hasNext()) { String iteratorValue=(String)it.next(); System.out.println("Queue Next Value :"+iteratorValue); } // get value and does not remove element from queue System.out.println("Queue peek :"+qe.peek()); // get first value and remove that object from queue System.out.println("Queue poll :"+qe.poll()); System.out.println("Final Size of Queue :"+qe.size()); } }
Output
Initial Size of Queue :5
Queue Next Value :b
Queue Next Value :a
Queue Next Value :c
Queue Next Value :e
Queue Next Value :d
Queue peek :b
Queue poll :b
Final Size of Queue :4
Tags: Collections



Link to Us
where is the implementation of the poll() and peek() methods?
I got it now, the implementation is in the imported package: import java.util.Queue;
peek()
Retrieves, but does not remove, the head (first element) of this list
poll()
Retrieves and removes the head (first element) of this list.
thx a lot! this is so helpfull
guysss can you help me . the user will input the item .can you help me to how to do that .. ? plssssssss ??reply with this ss
just use the this to add user input to the queue..
in this case its.
qe.add(the variable of users input);
for example..
qe.add(name);
where the name stores the value entered by the user..
C:\QueueExample.java:9: ‘(’ or ‘[’ expected
Queue qe=new LinkedList();
^
1 error
Process completed.
This is my output….
What did I do wrong?
is it possible to display all the inputed items on the queue list? example, I inputted numbers 1 2 3 and 6 and placed it on queue – ithen i will print THE NUMBERS ON QUEUE are 1 2 3 6? is this possible? If yes.. HOW? please need some help.. ><
why it should be implemented by LinkedList