Queues

Queues are used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list. it follows the FIFO (First-In-First-Out) principle. There are many different types of queues but the mist commonly used ones are the PriorityQueue and LinkedList.

Creating Queue Objects

Different types of Queues can be created in different ways:

Queue a = new PriorityQueue();
Queue b = new LinkedList();

Type-safe Queues can be defined in the following way:

Queue<Obj> queue = new LinkedList<Obj>();
Queue<Integer> queue = new LinkedList<Integer>(); // creates an integer queue

Operations on Queues

In addition to the operations of Collections, Queue also provide the following operations:

  • boolean add(Object element): This method is used to add elements at the tail of queue.
  • Object peek()- This method is used to view the head of queue without removing it. It returns Null if the queue is empty.
  • Object remove(): This method removes and returns the head of the queue. It throws an Exception when the queue is empty.
  • Object poll()- This method removes and returns the head of the queue. It returns null if the queue is empty.

Working with Queues

The following java program demonstrates working with Queues:

// Creates a Queue
Queue<Integer> q = new LinkedList<Integer>(); 

// Adds elements {0, 1, 2, 3, 4} to queue 
for (int i=0; i<5; i++) {
    q.add(i); 
}

// Display contents of the queue. 
System.out.println(q); // outputs [0, 1, 2, 3, 4]

// To remove the head of queue. 
System.out.println(q.remove()); // outputs 0
System.out.println(q); // outputs [1, 2, 3, 4]

// To view the head of queue 
System.out.println(q.peek()); // outputs 1

Source:

results matching ""

    No results matching ""