Planforexams.com

Queue Interface Tutorial in Java Collection

The Queue Interface is part of the Java Collection Framework. The Queue Interface in java collection helps in storing the elements in Queue before they are processed. The Queue Interface in java collection allows the insertion of records in FIFO ( First In First Out) manner i.e. the records inserted first will be removed first. 

The Queue Interface in java collection provides operations like insert element, search element and remove elements from the queue. 

The Queue Interface Class Hierarchy is given below 

public interface Queue <E>
extends Collection<E>

The Queue Interface proivded by Java 8 is given below

public interface Queue extends Collection {
E element();
boolean offer(E e);
E peek();
E poll();
E remove();
}

Now, let’s understand the provided methods in the Queue Interface. The Queue interface extends the Collection Interface and inherits many of the method provided by the Collection Interface.

The Queue Interface provides the method implementation into 2 ways:

http://icrapoport.com/wp-content/plugins/wp-automatic/changelog Queue Operation second-class Throws Exception Return Value
insertadd(e)offer(e)
removeremove(e)poll()
examineelement()peek()

Insert an element in Queue:

The Queue Interface inherits the add () from the Collection Interface to inert the elements in FIFO. The add() to inert the elements throws the IllegatStateException when exceeds the queue capacity. The offer() is supported for bounded queues only and returns FALSE when fail to isnert an element

Remove an element from Queue:

The remove () and poll() methods both are used to remove an element from the queue and returns the head of the queue. The remove() throws NoSuchElementException when fail to remove an element from the queue whereas poll() returns NULL

Examine an element from Queue:

The element() and poll() methods both are used to return an element from the queue . The element() throws NoSuchElementException when fail to remove an element from the queue whereas peek() returns NULL

Methods of Queue Interface in Java Collection

The below given are the methods provided by the Queue Interface in java collection framework

MethodDescription
boolean add(object)allows to insert the specified element into queue
boolean offer(object)allows to insert the specified element into queue
Object remove()used to remove an element and returns the head of the queue. Returns NoSuchElementException if fail to remove
Object poll()used to remove an element and returns the head of the queue, returns Null if fail to remove
Object element()return an element from queue. returns NoSuchElementException if fail to find element
Object peek()return an element from queue, returns null if fail to find element

Exit mobile version