Queue Overview
Queue is the linear data structure that follows a first-in-first-out (FIFO) order. It is a pre-defined Interface present in java.util package, Introduced from JDK1.5.
The primary implementation classes of the queue is
- PriorityQueue
- LinkedList
Important Methods of Queue
- enQue() - This method will add an object into Queue at the rear end.
- deQue() - This method will remove the object from the Queue from the front end.
- isFull() - returns true if the Queue is full.
- isEmpty() - returns true if Queue is empty.
- display() - returns all the objects present in Queue.
Features
- Priority Queue is an Implementation class of Queue Interface.
- Present in java.util pack and introduced from JDK1.5
- Only comparable type objects can be inserted in the Priority Queue.
Methods of Priority Queue
Method | Description |
boolean add(object); | It is used to insert the element into this queue and return true upon success. |
Object remove(); | It is used to remove the head object of this queue. |
Object poll(); | It is used to remove the object object from the head, or return null if Queue is empty. |
Object peak(); | It is used to retrieve or read the head object of this Queue. Or return null if the retrieveQueue is empty. |
Object element(); | It is used to retrieves, but doesn't remove, the head of this Queue. |
package com.quipoin;
import java.util.PriorityQueue;
public class QueueDemo {
public static void main(String[] args) {
PriorityQueue<Integer> queue=new PriorityQueue<>();
queue.add(10);
queue.add(20);
queue.add(30);
queue.add(40);
queue.add(50);
System.out.println(queue);
queue.poll();//retrieves and removes head element
System.out.println(queue);
System.out.println("--------------------");
queue.clear();//This method will clear the elements from the Queue.
System.out.println(queue);
}
}
Output:
[10, 20, 30, 40, 50]
[20, 40, 30, 50]
Key Point
- Queue follows FIFO principle.
- Priority Queue orders elements based on natural ordering or a comparator.
- Queue methods help efficiently manage elements.
- PriorityQueue not allow null elements.
- It is not thread-safe.
Two Minute Drill
- Use Queue when you need an ordered data structure following FIFO.
- Use PriorityQueue when priority-based ordering is required.