Java Queue Interface

tutorial and example
tutorial and example

JAVA QUEUE INTERFACE

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional operations of insertion, removal and inspection operations. It has offer(e) method for inserting, poll() method for removing, peek() for examine etc.

Generally but not necessarily, Queue orders its elements in FIFO(first in first out) manner.

We can also use priority queue to change the priority.

Since queue is an interface, in order to use it, we have to instantiate a concrete implementation.  We can use LinkedList or ArrayDeque which implements queue interface as well as deque interface. ArrayDeque can be used both as stack and queue. It is faster than stack and when it is used as queue, it is faster than linkedlist.

useful methods

Method

Description

For queue

For stack

E remove()

It removes and returns next element or throws an exception if empty queue.

Yes

No

void push(E e)

It adds an element to the front of the queue

Yes

Yes

E poll()

It removes and returns next element or returns null if empty queue.

Yes

No

E peek()

It returns next element or returns null if empty queue.

Yes

Yes

E pop()

It removes and returns next element or throws an exception if empty queue.

No

Yes

boolean add(E e)

It adds an element to the back of the queue and returns true or throws an exception.

Yes

No

E element()

It returns next element or throws an exception if empty queue.

Yes

No

boolean offer(E e)

It adds an element to the back of the queue and returns whether successful.

Yes

No

 

Example:

Output: