Queue Interface - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Saturday, November 26, 2016

Queue Interface

The Queue interface extends Collection interface and declare the behavior of a queue that supports the first-in, first-out elements.

Queue is a generic interface that has this declaration:

public interface Queue<E> extends Collection<E>

Here, E specifies the type of objects that the list will hold.

In addition to the methods defined by Collection, Queue defines some of its own method.

Method Description
E element( ) Returns the element at the head of the queue. The element is not removed. It throws NoSuchElementException if the queue is empty.
E peek( ) Returns the element at the head of the queue. The element is not removed. It returns null if the queue is empty.
E poll( ) Returns the element at the head of the queue, removing the element in the process. It returns null if the queue is empty.
E remove( ) Removes the element at the head of the queue, returning the element in the process. It throws NoSuchElementException if the queue is empty.
boolean offer(E obj) Attempts to add obj to the queue. Returns true if obj was added and false otherwise.

Most Commonly thrown Exceptions in Queue

Exception Description
ClassCastException occurs when an attempt is made to add an incompatible object in a queue.
NullPointerException will throw when you try to store a null object and null element is not allowed in the queue.
IllegalArgumentException will throw when an invalid argument is used.
IllegalStateException thrown if an attempt is made to add an element to a fixed-length queue that is full.
NoSuchElementException thrown if an attempt is made to remove an element from an empty queue.

No comments :

Post a Comment