Queue example in Java

Java provides us Queue interface, where we can keep and handle elements before processing. Except the methods that Collection provides, it also supports some basic operations in order to simulate the classic queue structure. Each of these operations exists in two forms:

1. if a method fails, an exception is thrown. This form includes add(), remove() and element() methods.
2. if a method fails, a special value is returned (null or false). This form contains offer(), poll() and peek() operations.

The interface Queue is defined as below

Queue_interface

[Java Doc]
The add method, which Queue inherits from Collection, inserts an element unless it would violate the queue’s capacity restrictions, in which case it throws IllegalStateException. The offer method, which is intended solely for use on bounded queues, differs from add only in that it indicates failure to insert an element by returning false.

The remove and poll methods both remove and return the head of the queue. Exactly which element gets removed is a function of the queue’s ordering policy. The remove and poll methods differ in their behavior only when the queue is empty. Under these circumstances, remove throws NoSuchElementException, while poll returns null.

The element and peek methods return, but do not remove, the head of the queue. They differ from one another in precisely the same fashion as remove and poll: If the queue is empty, element throws NoSuchElementException, while peek returns null.

Example:

output
Adding items to the Queue
Items in the queue...[Red, Black, White]
============================
queue.remove() removes element: Red
Items in the queue...[Black, White]
============================
queue.element() retrieves element: Black
Items in the queue...[Black, White]
============================
queue.poll() removes and retrieves element, null if empty: Black
Items in the queue...[White]
============================
queue.peek() retrieves element, null is empty White
Items in the queue...[White]
============================

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">