Queue Interface in Java
In the previous blog, we learned about TreeSet in Java. If you want to know more about it visit TreeSet in Java. In this blog, we will go through Queue Interface. We all are familiar with the word Queue. In general, Queue is nothing but a line of people or vehicles waiting for something. For example, people waiting at the ticket counter or ATM. A similar concept is followed in Queue Interface in Java.
Queue Interface
Queue interface follows the FIFO approach i.e. First In First Out. As the Queue Interface follows the FIFO approach, the elements in the Queue are stored in a sequential manner i.e. in an ordered list where adding or insertion of elements is done at the end and removal or deletion is done at the beginning. As Queue is an interface it required a concrete class for declaration. The most common classes are LinkedList and PriorityQueue.
Declaration of Queue Interface
Syntax
Program to demonstrate Queue Interface
Output
Methods of Queue Interface
- add()
- offer()
- element()
- remove()
- peek()
- poll()
add() method is used for adding or inserting the specific element into the queue. If the element is inserted successfully then it returns true, else it throws an exception on failure.
e.g.
Output
offer() method is used for adding or inserting the specific element into the queue. If the element is inserted successfully then it returns true, else returns false
e.g.
Output
element() returns the head of the queue. It throws an exception if the queue is empty.
e.g.
Output
remove() returns and removes the head of the queue. It throws an exception if the queue is empty.
e.g.
Output
peek() method returns the head of the queue. If the queue is empty it returns null.
e.g.
Output
poll() method returns and removes the head of the queue. If the queue is empty it returns null.
e.g.
Output
Implementation of LinkedList
e.g.
Output
Implementation of PriorityQueue
e.g.
Output