www.000webhost.com
/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Queue interface


Queue Interface


Core Java

The java.util.Queue interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects just like a List, but its intended use is slightly different.

A queue is aFIFO sequence, A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue.



package javaessential.com;

/**
 * A small queue interface.  You can query the size of the queue and
 * ask whether it is empty, add and remove items, and peek at the front
 * item.
 */
public interface Queue {

    /**
     * Adds the given item to the rear of the queue.
     */
    void enqueue(Object item);

    /**
     * Removes the front item from the queue and returns it.
     * @exception java.util.NoSuchElementException if the queue is empty.
     */
    Object dequeue();

    /**
     * Returns the front item from the queue without popping it.
     * @exception java.util.NoSuchElementException if the queue is empty.
     */
    Object peek();

    /**
     * Returns the number of items currently in the queue.
     */
    int size();

    /**
     * Returns whether the queue is empty or not.
     */
    boolean isEmpty();
}

Table of contents:

Queue Implementations

Adding and Accessing Elements

Iterating in Queue

Removing Elements

Generic Queues

Queue Example


Here is first a simple Java Queue example to give you a feel for how sets work:



Queue Implementations

Since Queue is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Queue implementations in the Java Collections API:

java.util.LinkedList

java.util.PriorityQueue


LinkedList is a pretty standard queue implementation.
PriorityQueue stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue.

There are also Queue implementations in the java.util.concurrent package - we are not going to discuss about it here.


Here are a few examples of how to create a Queue instance:

Here are a few examples of how to create a Queue instance:
Queue queueA = new LinkedList();
Queue queueB = new PriorityQueue();

Adding and Accessing Elements

Queue queueA = new LinkedList();

queueA.add("element 1");
queueA.add("element 2");
queueA.add("element 3");

The order in which the elements added to the Queue are stored internally, depends on the implementation.

The same is true for the order in which elements are retrieved from the queue. You should consult the JavaDoc's for more information about the specific Queue implementations.

You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the element() method. Here is how that looks:

Object firstElement = queueA.element();

To take the first element out of the queue, you use the remove() method which is described later.
You can also iterate all elements of a queue, instead of just processing one at a time. Here is how that looks:

	Queue queueA = new LinkedList();
	
	queueA.add("element 0");
	queueA.add("element 1");
	queueA.add("element 2");
	
	//access via Iterator
	Iterator iterator = queueA.iterator();
	while(iterator.hasNext()
	{
	  String element = (String) iterator.next();
	}
	
	//access via new for-loop
	for(Object object : queueA) 
	{
	    String element = (String) object;
	}

When iterating the queue via its Iterator or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the queue implementation.


iterating Elements in Queue


		Queue queue1 = new LinkedList();
		queue1.add("element 0");
		queue1.add("element 1");
		queue1.add("element 2");
		 
		//access via Iterator
		Iterator iterator = queue1.iterator();
		while(iterator.hasNext(){
		  String element = (String) iterator.next();
		}
		 
		//access via new for-loop
		for(Object object : queue1) {
		    String element = (String) object;
		}

Removing Elements

To remove elements from a queue, you call the remove() method. This method removes the element at the head of the queue.

In most Queue implementations the head and tail of the queue are at opposite ends. It is possible, however, to implement the Queue interface so that the head and tail of the queue is in the same end. In that case you would have a stack.
Here is a remove example();


Object firstElement = queueA.remove();


Generic Queue

By default you can put any Object into a Queue, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a Queue. Here is an example:

Queue queue = new LinkedList();


This Queue can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks

	MyObject myObject = queue.remove();
	
	for(MyObject anObject : queue){
	   //do someting to anObject...   
	}

Few Examples on Queue

Queue Methods using the add() - Java source Code


		package javaessential.com;
		import java.util.*;
		public class QueueExamplewithAdd 
		{
		        public static void main(String[] args) 
		        {
		
		        Queue oqueue=new LinkedList();
		
		        oqueue.add("1");
		        oqueue.add("2");
		        oqueue.add("3");
		        oqueue.add("4");
		        oqueue.add("5");
		
		        Iterator itr=oqueue.iterator();
		        System.out.println("Initial Size of Queue :"+oqueue.size());
		
		        while(itr.hasNext())
		        {
		            String iteratorValue=(String)itr.next();
		            System.out.println("Queue Next Value :"+iteratorValue);
		        }
		
		        // get value and does not remove element from queue
		        System.out.println("Queue peek :"+oqueue.peek());
		        // get first value and remove that object from queue
		        System.out.println("Queue poll :"+oqueue.poll());
		        System.out.println("Final Size of Queue :"+oqueue.size());
		    }
		}
		
	OutPut - 
			Initial Size of Queue :5
			Queue Next Value :1 			
			Queue Next Value :2 
			Queue Next Value :3 
			Queue Next Value :4 			
			Queue Next Value :5 			
			Queue peek :1 			
			Queue poll :1 			
			Final Size of Queue :4

Queue Methods using the offer() - Java source Code


The offer method inserts an element if possible, otherwise returning false


		package javaessential.com;
		import java.util.*;
		
		public class QueueExamplewithOffer 
		{
		        public static void main(String[] args) 
		        {
		                Queue queue = new LinkedList();
		                queue.offer("11");
		                queue.offer("22");
		                queue.offer("33");
		                queue.offer("44");
		
		                System.out.println("The size of the queue    : " + queue.size());
		                System.out.println("Queue head using peek    : " + queue.peek());
		                System.out.println("Queue head using element : " + queue.element());
		                System.out.println("The element of queue are : " + queue);
		
		                Object element;
		                while ((element = queue.poll()) != null) {
		                        System.out.println("The " + element + " is removed");
		                }
		                System.out.println("The Queue after removal : " + element);
		        }
		}
		
	OutPut - 
		The size of the queue : 4 
		Queue head using peek : 11
		Queue head using element : 11 		
		The element of queue are : [11, 22, 33, 44] 		
		The 11 is removed 		
		The 22 is removed		
		The 33 is removed
		The 44 is removed 
		The Queue after removal : null

Click here to continue reading Iterable Interface