The Queue interface is available in java.util
package and extends the collection interface. A queue1 is an ordered list of objects with its use limited to insert elements at the end of a list and deleting elements from the start of a list. It follows the First-In-First-Out (FIFO) principle.
Below is a visualization of the insertion of objects in a queue. Objects are always inserted at the tail of the queue.
Below is a visualization of the removal of objects in a queue. Objects are always removed from the head of the queue.
The most common classes that implement Queue interface in Java are:
add(): is used to add an element at the tail of the queue. The element to be inserted is passed as the parameter. The method throws an exception if the operation is unsuccessful, and returns true
if the operation is successful.
offer(): is used to add an element at the tail of the queue. The element to be inserted is passed as the parameter. The method returns false
if the operation is unsuccessful, and returns true
if the operation is successful.
remove(): returns the head of the queue and removes it. The method throws an exception if the queue is empty.
poll(): the remove()
method returns the head of the queue and removes it. It returns null
if the queue is empty.
peek(): returns the head of the queue without removing it. It returns null
if the queue is empty.
element(): the peek()
method returns the head of the queue without removing it. It throws an exception if the queue is empty.
size(): returns the number of elements in the queue.
isEmpty(): returns true
if the queue is empty, otherwise it returns false
.
Free Resources