queue

Queue Interface in Java with Programming Example

queueIn this chapter you will learn:

  1. What is queue interface?
  2. Queue Structure
  3. Programming Example
 What is Queue Interface?

Queue is a part of java collection that follows FIFO structure for holding elements. FIFO is based on First In First Out that means the first inserted element will be processed first. There are various real life examples of Queues are:

  • Ticket Counter Queue – The First person in the line gets chance to buy ticket first.
  • Bus Queue – First position bus will start first.
  • Billing Counter – First customer in the line will pay the bill first.

More about Queue

  1. Queue has additional insertion, removal and inspection operations besides on basic collection operations.
  2. Each Queue operation gets terminated by two methods either by throwing exception or by returning special value as null or false.
  3. Each queue has two parts head and tail. Items inserted in queue through tail side and remove item through head side.
  4. Bounded queue holds only specified number of elements.
  5. Add() method is used for inserting element in a queue and remove() or poll() method is used for removing items from queue.
  6. Queue doesn’t allow the insertion of null.
 Methods of Queue Interface
MethodsDescriptions
boolean add (E e)This method inserts an element in a queue and returns true if operation successful or return IllegalStateException exception.
E element( )This method returns element from the top of the queue. It only retrieves element and returns to you. It doesn’t remove element.
boolean offer(E e)This method is also used for adding element in a queue. It is useful when queue is bounded and accept only limit number of element. It returns true if element is added successfully and return false if operation fails. The add(E e)method throws exception when operation gets unsuccessful.
E peek( )This methods returns element from the top of the queue. The difference between E element() and E peek() method is E peek() returns null if element not found whereas E element throws NoSuchElementExceptionexception.
E poll()This methods removes item from the top of the queue. It returns null if operation gets failed.
E remove()It also removes item from the top of the queue but returnsNoSuchElementException if queue is empty.

Declaration

Programming Example

Output

Size of queue : 5
Java C# VB.Net C++ PHP
Top Item is Java
Items Removed Java
[C#, VB.Net, C++, PHP]
Size of queue : 4
[C#, VB.Net, C++, PHP, HTML]
_

Summary

In this chapter you learned what the queue interface is in java and their methods and implementation with programming example. In the next chapter you will learn PriorityQueue class.


Leave a Reply

Your email address will not be published. Required fields are marked *