Difference between PriorityQueue and Queue Implementation in Java
Last Updated :
18 Jan, 2024
Java Queue Interface
The Java.util package has the interface Queue, which extends the Collection interface. It is employed to preserve the components that are handled according to the FIFO principle. It is an ordered list of items where new elements are added at the end and old elements are removed from the beginning.
Being an interface, the queue needs a concrete class for the declaration, and the most popular classes in Java are the LinkedList and PriorityQueue. These classes' implementations are not thread-safe. PriorityBlockingQueue is a viable solution if a thread-safe implementation is necessary.
Declaration :
public interface Queue<E> extends Collection<E>
Methods of Java Queue Interface:
|
boolean add(object) | Inserts the specified element into the queue and returns true if successful. |
boolean offer(object) | Inserts the specified element into the queue. |
Object remove() | Used to retrieve and remove the queue's head. |
Object poll() | return null if the queue is empty; else, it obtains and removes queue's head. |
Object element() | It does retrieve, but does not remove, the queue's head. |
Object peek() | returns null if the queue is empty, else it obtains the head of the queue without removing it. |
Features of a Queue
- A queue's items are added to and removed using the FIFO paradigm.
- All of the Collection interface's methods, such as deletion, insertion, etc., are supported by the Java Queue.
- LinkedList, ArrayBlockingQueue, and PriorityQueue are the most popular implementations of queue.
- Any null operation on the blocking queues results in the NullPointerException being thrown.
- Unbounded Queues are those Queues that are included in the util package.
- Bounded Queues are those Queues that are included in the util.concurrent package.
- All queues, with the exception of the Deques, make it easy to get in and out at the front and back of the line, respectively. Deques actually allow for element removal and insertion at both ends.
Implementation of Queue :
Java
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args)
{
Queue<Integer> q
= new LinkedList<>();
// Elements {10, 20, 30, 40, 50} are added to the queue
for (int i = 10; i <= 50; i += 10)
q.add(i);
// Printing the contents of queue.
System.out.println("The Elements of the queue are : "
+ q);
// Removing queue's head.
int x = q.remove();
System.out.println("Removed element - "
+ x);
System.out.println(q);
// Viewing queue's head
int head = q.peek();
System.out.println("Head of the queue - "
+ head);
int size = q.size();
System.out.println("Size of the queue - "
+ size);
}
}
OutputThe Elements of the queue are : [10, 20, 30, 40, 50]
Removed element - 10
[20, 30, 40, 50]
Head of the queue - 20
Size of the queue - 4
PriorityQueue Class
Another class defined in the collection framework, PriorityQueue, provides a method for prioritising objects as they are processed. In the Java queue, object insertion and deletion are described as following a FIFO pattern. However, a PriorityQueue can be used when it is necessary to process queue elements in accordance with their priority.
Declaration :
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Methods of Java PriorityQueue Class:
|
boolean add(E e) | Adds element e to the PriorityQueue. |
void clear() | Clears the PriorityQueue by deleting all the elements. |
Comparatorcomparator() | Returns a custom comparator used for the ordering of elements in the Queue. |
boolean contains(Object o) | Checks whether the given element o is present in the PriorityQueue. if yes, returns true. |
Iterator< E >iterator() | Gets an iterator for the given PriorityQueue. |
boolean offer(E e) | Insert given element e to the PriorityQueue. |
E peek() | Used to return the head of the queue without deleting the element. |
E poll() | If the queue is empty, returns null otherwise it removes and returns the head of the queue. |
int size() | Returns the number of elements in PriorityQueue. |
Object[] toArray() | Used to return an array representation of the PriorityQueue. |
T[] toArray(T[] a) | Used to return an array representation for the Priority Queue with the same runtime type as the specified array a. |
Characteristics of a PriorityQueue:
- PriorityQueue is an unbound queue.
- PriorityQueue does not permit null values. A priority queue cannot be created for non-comparable objects.
- It inherits from classes such as Collection, AbstractCollection, AbstractQueue, and Object.
- The head/front of the queue contains the least element according to the natural ordering.
- The implementation of the priority queue is not thread-safe. Therefore, we should use the PriorityBlockingQueue if we want synchronised access.
Implementation of PriorityQueue :
Java
// Java program demonstrating PriorityQueue's working
import java.util.*;
class PriorityQueueTest {
// Main Method
public static void main(String args[])
{
// Empty priority queue is created
PriorityQueue<String> pq = new PriorityQueue<String>();
// Using add() to add items to pq
pq.add("Ram");
pq.add("Mohan");
pq.add("Sohan");
// displaying top element of PriorityQueue
System.out.println(pq.peek());
// displaying the top element and removing it from the PriorityQueue container
System.out.println(pq.poll());
// Top element of pq is printed again
System.out.println(pq.peek());
}
}
Difference between Queue and PriorityQueue Implementation :
|
Queue is a linear data structure. | Priority Queue is an extension of Queue with priority factor embedded. |
Follows First In First Out (FIFO) algorithm to serve the elements. | Serves the element with higher priority first. |
Enqueue and dequeue done in O(1). | Enqueue and dequeue done in O(log n) using binary heaps. |
Used in algorithms such as Breadth First Search. | Used in algorithms such as Dijkstra's Algorithm, Prim's Algorithms, CPU Scheduling. |
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read