Java Queue Interface

The Queue is an interface, it is present in java.util package and it extends the Collection interface. Queue will process the elements in FIFO(First In First Out) order.

Queue interface classes.

  1. ▪ ArrayDeque
  2. ▪ LinkedList
  3. ▪ PriorityQueue

interfaces that extends Queue
  1. ▪ Deque
  2. ▪ BlockingQueue
  3. ▪ BlockingDeque
Working of Queue data structures

In queues, elements are stored and accessed in First In, First Out manner. That is, elements are added from the behind and removed from the front.


How to use Queue

We must import java.util.Queue package in order to use Queue


                    // LinkedList implementation of Queue
                    Queue<String< animal1 = new LinkedList<>();
                    
                    // Array implementation of Queue
                    Queue<String< animal2 = new ArrayDeque<>();
                    
                    // Priority Queue implementation of Queue
                    Queue<String< animal 3 = new PriorityQueue<>();
                  

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

  1. add() - Inserts the specified element into the queue. If the task is successful, add() returns true, if not it throws an exception.
  2. offer() - Inserts the specified element into the queue. If the task is successful, offer() returns true, if not it returns false.
  3. element() - Returns the head of the queue. Throws an exception if the queue is empty.
  4. peek() - Returns the head of the queue. Returns null if the queue is empty.
  5. remove() - Returns and removes the head of the queue. Throws an exception if the queue is empty.
  6. poll() - Returns and removes the head of the queue. Returns null if the queue is empty.