Queue-Overview
Queue Interface
- Queue is the linear data structure that follows a first-in-first-out (FIFO) order. The implementation classes of Queue Interface are Priority Queue and LinkedList.
- Queue is a pre-defined Interface present in java.util package, Introduced from JDK1.5.
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.
Priority Queue
Key points:
- 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. |
Example:
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]