Java Queue interface

Java Queue interface

The interface Queue is available in the java.util package and does extend the Collection interface. It is used to keep the elements that are processed in the First In First Out (FIFO) manner. It is an ordered list of objects, where insertion of elements occurs at the end of the list, and removal of elements occur at the beginning of the list.

Being an interface, the queue requires, for the declaration, a concrete class, and the most common classes are the LinkedList and PriorityQueue in Java. Implementations done by these classes are not thread safe. If it is required to have a thread safe implementation, PriorityBlockingQueue is an available option.

Queue Interface Declaration

  1. public interface  Queue<E>  extends  Collection<E>  

    Methods of Java Queue Interface

MethodDescription
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

PriorityQueue is also class that is defined in the collection framework that gives us a way for processing the objects on the basis of priority. It is already described that the insertion and deletion of objects follows FIFO pattern in the Java queue. However, sometimes the elements of the queue are needed to be processed according to the priority, that's where a PriorityQueue comes into action.

PriorityQueue Class Declaration

Let's see the declaration for java.util.PriorityQueue class.

  1. public class  PriorityQueue<E>  extends  AbstractQueue<E>  implements  Serializable  

Java PriorityQueue Example

FileName: TestCollection12.java

  1. import java.util.*;

  2. class TestCollection12{

  3. public static void main(String args[]){

  4. PriorityQueue<String> queue=new PriorityQueue<String>();

  5. queue.add("Amit");

  6. queue.add("Vijay");

  7. queue.add("Karan");

  8. queue.add("Jai");

  9. queue.add("Rahul");

  10. System.out.println("head:"+queue.element());

  11. System.out.println("head:"+queue.peek());

  12. System.out.println("iterating the queue elements:");

  13. Iterator itr=queue.iterator();

  14. while(itr.hasNext()){

  15. System.out.println(itr.next());

  16. }

  17. queue.remove();

  18. queue.poll();

  19. System.out.println("after removing two elements:");

  20. Iterator<String> itr2=queue.iterator();

  21. while(itr2.hasNext()){

  22. System.out.println(itr2.next());

  23. }

  24. }

  25. }

    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

    Let's see a PriorityQueue example where we are adding books to queue and printing all the books. The elements in PriorityQueue must be of Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in PriorityQueue, you need to implement Comparable interface.

    FileName: LinkedListExample.java

    1. import java.util.*;

    2. class Book implements Comparable<Book>{

    3. int id;

    4. String name,author,publisher;

    5. int quantity;

    6. public Book(int id, String name, String author, String publisher, int quantity) {

    7. this.id = id;

    8. this.name = name;

    9. this.author = author;

    10. this.publisher = publisher;

    11. this.quantity = quantity;

    12. }

    13. public int compareTo(Book b) {

    14. if(id>b.id){

    15. return 1;

    16. }else if(id<b.id){

    17. return -1;

    18. }else{

    19. return 0;

    20. }

    21. }

    22. }

    23. public class LinkedListExample {

    24. public static void main(String[] args) {

    25. Queue<Book> queue=new PriorityQueue<Book>();

    26. //Creating Books

    27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);

    28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);

    29. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

    30. //Adding Books to the queue

    31. queue.add(b1);

    32. queue.add(b2);

    33. queue.add(b3);

    34. System.out.println("Traversing the queue elements:");

    35. //Traversing queue elements

    36. for(Book b:queue){

    37. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

    38. }

    39. queue.remove();

    40. System.out.println("After removing one book record:");

    41. for(Book b:queue){

    42. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

    43. }

    44. }

    45. }

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

Java Deque Interface

The interface called Deque is present in java.util package. It is the subtype of the interface queue. The Deque supports the addition as well as the removal of elements from both ends of the data structure. Therefore, a deque can be used as a stack or a queue. We know that the stack supports the Last In First Out (LIFO) operation, and the operation First In First Out is supported by a queue. As a deque supports both, either of the mentioned operations can be performed on it. Deque is an acronym for "double ended queue".

Deque Interface declaration

  1. public interface  Deque<E>  extends  Queue<E>  

Methods of Java Deque Interface

MethodDescription
boolean add(object)It is used to insert the specified element into this deque and return true upon success.
boolean offer(object)It is used to insert the specified element into this deque.
Object remove()It is used to retrieve and removes the head of this deque.
Object poll() -->It is used to retrieve and removes the head of this deque, or returns null if this deque is empty.
Object element() -->It is used to retrieve, but does not remove, the head of this deque.
Object peek()It is used to retrieve, but does not remove, the head of this deque, or returns null if this deque is empty.
Object peekFirst()The method returns the head element of the deque. The method does not remove any element from the deque. Null is returned by this method, when the deque is empty.
Object peekLast()The method returns the last element of the deque. The method does not remove any element from the deque. Null is returned by this method, when the deque is empty.
Boolean offerFirst(e)Inserts the element e at the front of the queue. If the insertion is successful, true is returned; otherwise, false.
Object offerLast(e)Inserts the element e at the tail of the queue. If the insertion is successful, true is returned; otherwise, false.

ArrayDeque class

We know that it is not possible to create an object of an interface in Java. Therefore, for instantiation, we need a class that implements the Deque interface, and that class is ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection class.

The important points about ArrayDeque class are:

  • Unlike Queue, we can add or remove elements from both sides.

  • Null elements are not allowed in the ArrayDeque.

  • ArrayDeque is not thread safe, in the absence of external synchronization.

  • ArrayDeque has no capacity restrictions.

  • ArrayDeque is faster than LinkedList and Stack.

ArrayDeque Hierarchy

The hierarchy of ArrayDeque class is given in the figure displayed below.

java arraydeque hierarchy

ArrayDeque class declaration

Let's see the declaration for java.util.ArrayDeque class.

  1. public class  ArrayDeque<E>  extends  AbstractCollection<E>  implements  Deque<E>, Cloneable, Serializable  

Java ArrayDeque Example

FileName: ArrayDequeExample.java

  1. import  java.util.*;

  2. public class ArrayDequeExample {

  3. public static void main(String[] args) {

  4. //Creating Deque and adding elements

  5. Deque<String> deque =  new  ArrayDeque<String>();

  6. deque.add("Ravi");

  7. deque.add("Vijay");

  8. deque.add("Ajay");

  9. //Traversing elements

  10. for (String str : deque) {

  11. System.out.println(str);

  12. }

  13. }

  14. }

Output:

Ravi
Vijay
Ajay

Java ArrayDeque Example: offerFirst() and pollLast()

FileName: DequeExample.java

  1. import java.util.*;

  2. public class DequeExample {

  3. public static void main(String[] args) {

  4. Deque<String> deque=new ArrayDeque<String>();

  5. deque.offer("arvind");

  6. deque.offer("vimal");

  7. deque.add("mukul");

  8. deque.offerFirst("jai");

  9. System.out.println("After offerFirst Traversal...");

  10. for(String s:deque){

  11. System.out.println(s);

  12. }

  13. //deque.poll();

  14. //deque.pollFirst();//it is same as poll()

  15. deque.pollLast();

  16. System.out.println("After pollLast() Traversal...");

  17. for(String s:deque){

  18. System.out.println(s);

  19. }

  20. }

  21. }

Output:

After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal

Java ArrayDeque Example: Book

FileName: ArrayDequeExample.java

  1. import java.util.*;

  2. class Book {

  3. int id;

  4. String name,author,publisher;

  5. int quantity;

  6. public Book(int id, String name, String author, String publisher, int quantity) {

  7. this.id = id;

  8. this.name = name;

  9. this.author = author;

  10. this.publisher = publisher;

  11. this.quantity = quantity;

  12. }

  13. }

  14. public class ArrayDequeExample {

  15. public static void main(String[] args) {

  16. Deque<Book> set=new ArrayDeque<Book>();

  17. //Creating Books

  18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

  19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

  20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

  21. //Adding Books to Deque

  22. set.add(b1);

  23. set.add(b2);

  24. set.add(b3);

  25. //Traversing ArrayDeque

  26. for(Book b:set){

  27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

  28. }

  29. }

  30. }

Output:

101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6