Java - Core Java - Collection Framework - Queue


  • 1.5 Enhancements (Queue Interface). It is the child interface of collection.
  • If we want to represent a group of individual objects prior to processing then we should go for Queue. e.g. Before sending SMS to all mobile number we have to store in some data structure in which order mobile number in the same order only message should be sent or delivered. For this FIFO requirement Queue is the best choice.
  • It follows FIFO order but based on our requirement, we can implement our own priority order also Priority Queue.
  • From 1.5 version onwards LinkedList class also implements Queue interface.
  • LinkedList implementation of queue always follows FIFO order.
  • PriorityQueue

  • If we want to represent a group of individual objects prior to processing according to some priority then we should go for PriorityQueue.
  • The priority can be either DNSO(default natural sorting order) or CSO(customized sorting order) defined by comparator.
  • Insertion order is not preserved; it is based on some priority.
  • Duplicate objects are not allowed.
  • If we are depending on default natural sorting order, compulsorily the object should be homogeneous and comparable otherwise we will get a Runtime exception saying ClassCastException.
  • If we define our own sorting by comparator then object need not be homogeneous and comparable.
  • Null insertion is not allowed even as first element also.
  • Program
    import java.util.*;
    public class QueueDemo {
        public static void main(String[] args) {
            PriorityQueue pq=new PriorityQueue();
            for (int i = 0; i < 10; i++) 
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    [1, 3, 2, 7, 4, 5, 6, 9, 8]