Way2Java

Queue Tutorial Java

Queue Tutorial Java: interface Queue was introduced with JDK 1.5 and is part of collections framework as Queue extends Collection interface. Queue stores elements in such way it returns the first one added. Queue follows the style of FIFO (first in, first out, remember stack follows LIFO, last in, first out). The first element in the queue is known as head and the last one is known as tail. New elements are added to the tail.

Following is the signature

public interface Queue extends Collection
Queue Tutorial

As queue is a subclass of Collection, it can make use of all the methods of Collection and also the extra defined in its own such as inserting, retrieving and checking the elements.

Queue vs List

The major variation is that list allows retrieving the elements from any position. But, queue follows FIFO. LinkedList implements both interfaces List and Queue.

Programming Tip: Queue allows null elements. But it is advised not to add null as the return type of poll() method is also null when the queue is empty. The return null value may confuse (or conflict) with the actual null value you have added.

Realtime examples of Queue

A Queue Program is given in Queue Offer Poll Peek Remove Elements Java using all the API methods.