View RSS Feed

Algorithm and Data Structure

Java Queue Example

Rate this Entry
by , 02-19-2012 at 07:00 AM (6599 Views)
Queue base is at first in first out policy. The Queue interface is present in java.util package. Queue size is not required to be specified just like it is done in arrays.

Functionality of Queue is explained in the given code.

Example of Queue
Java Code: This is the code to explain Java Queue
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class QueueTesting {

    public static void main(String[] args) {

        Queue<String> myQueue=new LinkedList<String>();

        myQueue.add("b");
        myQueue.add("a");
        myQueue.add("c");
        myQueue.add("e");
        myQueue.add("d");

        Iterator it= myQueue.iterator();

        System.out.println("Initial Size of Queue :"+ myQueue.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 :"+ myQueue.peek());

        // get first value and remove that object from queue
        System.out.println("Queue poll :"+ myQueue.poll());

        System.out.println("Final Size of Queue :"+ myQueue.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

Submit "Java  Queue Example" to Facebook Submit "Java  Queue Example" to Digg Submit "Java  Queue Example" to del.icio.us Submit "Java  Queue Example" to StumbleUpon Submit "Java  Queue Example" to Google

Tags: java queue Add / Edit Tags
Categories
Queue

Comments