dsa

Java Queue Interface

In this tutorial, we will learn about Queue Interface and it's methods in Java.

Java Collection frameworks provide Queue Interface which works on Queue data structure.It is present in java.util package and it implements Collection Interface.It works on the principle of First-In-First-Out(FIFO).

Characteristics of a Queue:

The following are the characteristics of the queue:

  • The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept.
  • The Java Queue supports all methods of Collection interface including insertion, deletion etc.
  • If any null operation is performed on BlockingQueues, NullPointerException is thrown.
  • The Queues which are available in java.util package are Unbounded Queues.
  • The Queues which are available in java.util.concurrent package are the Bounded Queues.
  • All Queues except the Deques supports insertion and removal at the tail and head of the queue respectively. The Deques support element insertion and removal at both ends.

Derived classes of Queue Interface

We can not create objects of an interface so we need derived-classes to create objects.So Java provided us 3 derived classes for our use.They are :

  1. PriorityQueue
  2. LinkedList
  3. ArrayDeque

Sub-Interfaces of Queue Interface

  1. Deque
  2. BlockingQueue
  3. BlockingDeque

Methods of Queue Interface

Some of the commonly used methods of the Queue interface are:

MethodsDescription
add(): It inserts the given element into the queue and return true.
offer(): It inserts the given element into the queue and return true.
element(): It returns the head of the queue. It throws an exception if the queue is empty.
peek():It returns the head of the queue and returns null if the queue is empty.
remove(): It returns and removes the head of the queue.It throws exception if found empty.
poll(): It returns and removes the head of the queue. Returns null if the queue is empty.