Java Queue Interface
The Queue interface in Java is a component of the java.util package. It is a key element of the Java Collections Framework created to manage items in a particular order, usually following a First-In-First-Out (FIFO) approach. Operating as a sequenced collection of items, a Queue guarantees that elements are added at the rear and taken out from the front, making it well-suited for use cases like arranging tasks, handling orders, and overseeing printing tasks.
As an abstraction, Queue cannot be directly created as an instance; it necessitates a specific implementation. In Java, the prevalent implementations of the Queue interface are LinkedList and PriorityQueue. LinkedList offers a doubly-linked list structure, and PriorityQueue utilizes a priority heap to organize elements based on their natural order or a custom comparator.
Nonetheless, the typical implementations lack thread safety, rendering them inadequate for scenarios involving concurrent operations where multiple threads might simultaneously access and update the queue. To address this, Java offers the PriorityBlockingQueue class within the java.util.concurrent package, delivering a thread-safe implementation of a priority queue.
The Queue interface is an extension of the Collection interface. It inherits all the methods from Collection and introduces additional methods specifically for adding, removing, and inspecting elements. Important methods in Queue are add and offer for adding elements, remove and poll for removing elements, and element and peek for inspecting elements. These methods are tailored to address the specific requirements of a queue, including returning specific values or raising exceptions in cases where operations fail because of capacity limits or an empty queue.
Queue Interface Declaration
public interface Queue<E> extends Collection<E>
Methods of Java Queue Interface
| Method | Description |
|---|---|
| boolean add(object) | It is used to insert the specified element into this queue and return true upon success. |
| boolean offer(object) | It is used to insert the specified element into this queue. |
| Object remove() | It is used to retrieves and removes the head of this queue. |
| Object poll() | It is used to retrieves and removes the head of this queue, or returns null if this queue is empty. |
| Object element() | It is used to retrieves, but does not remove, the head of this queue. |
| Object peek() | It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. |
Features of a Queue
The following are some important features of a queue.
- As discussed earlier, FIFO concept is used for insertion and deletion of elements from a queue.
- The Java Queue provides support for all of the methods of the Collection interface including deletion, insertion, etc.
- PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are used most frequently.
- The NullPointerException is raised, if any null operation is done on the BlockingQueues.
- Those Queues that are present in the util package are known as Unbounded Queues.
- Those Queues that are present in the util.concurrent package are known as bounded Queues.
- All Queues barring the Deques facilitates removal and insertion at the head and tail of the queue; respectively. In fact, deques support element insertion and removal at both ends.
PriorityQueue Class
The PriorityQueue class, present in the collection framework, allows for object processing based on priority. Unlike the FIFO pattern followed by Java queues for object insertion and deletion, PriorityQueue enables objects in the queue to be processed according to their priority when necessary.
PriorityQueue Class Declaration
Let's examine the declaration of the java.util.PriorityQueue class.
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Java PriorityQueue Example
FileName: TestCollection12.java
import java.util.*;
class TestCollection12 {
public static void main(String args[]) {
// Creating a PriorityQueue of Strings
PriorityQueue<String> queue = new PriorityQueue<String>();
// Adding elements to the PriorityQueue
queue.add("Amit");
queue.add("Vijay");
queue.add("Karan");
queue.add("Jai");
queue.add("Rahul");
// Displaying the head of the queue using element() method
// This method throws an exception if the queue is empty
System.out.println("head:" + queue.element());
// Displaying the head of the queue using peek() method
// This method returns null if the queue is empty
System.out.println("head:" + queue.peek());
// Iterating through the queue elements
System.out.println("iterating the queue elements:");
Iterator<String> itr = queue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// Removing the head of the queue using remove() method
// This method throws an exception if the queue is empty
queue.remove();
// Removing the head of the queue using poll() method
// This method returns null if the queue is empty
queue.poll();
// Displaying the queue elements after removing two elements
System.out.println("after removing two elements:");
Iterator<String> itr2 = queue.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
Output:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Java PriorityQueue Example: Book
Consider the following demonstration involving a PriorityQueue, where books are inserted into the queue and subsequently displayed. It is essential that the elements contained within a PriorityQueue are of a Comparable type. By default, both String and Wrapper classes are Comparable. Should you wish to include custom objects within a PriorityQueue, it becomes necessary to implement the Comparable interface.
FileName: LinkedListExample.java
import java.util.*;
class Book implements Comparable<Book> {
int id;
String name, author, publisher;
int quantity;
// Constructor to initialize Book object
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
// compareTo method to compare Books based on 'id'
public int compareTo(Book b) {
if (id > b.id) {
return 1;
} else if (id < b.id) {
return -1;
} else {
return 0;
}
}
}
public class LinkedListExample {
public static void main(String[] args) {
// Creating a PriorityQueue to store Book objects
Queue<Book> queue = new PriorityQueue<Book>();
// Creating Book objects
Book b1 = new Book(121, "Let us C", "Yashwant Kanetkar", "BPB", 8);
Book b2 = new Book(233, "Operating System", "Galvin", "Wiley", 6);
Book b3 = new Book(101, "Data Communications & Networking", "Forouzan", "Mc Graw Hill", 4);
// Adding Book objects to the queue
queue.add(b1);
queue.add(b2);
queue.add(b3);
// Displaying the elements of the queue
System.out.println("Traversing the queue elements:");
for (Book b : queue) {
System.out.println(b.id + " " + b.name + " " + b.author + " " + b.publisher + " " + b.quantity);
}
// Removing the head of the queue
queue.remove();
// Displaying the elements of the queue after removing one element
System.out.println("After removing one book record:");
for (Book b : queue) {
System.out.println(b.id + " " + b.name + " " + b.author + " " + b.publisher + " " + b.quantity);
}
}
}
Output:
Traversing the queue elements:
101 Data Communications & Networking Forouzan Mc Graw Hill 4
233 Operating System Galvin Wiley 6
121 Let us C Yashwant Kanetkar BPB 8
After removing one book record:
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6