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 a priority queue to change the priority.
Since the 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 the stack, and when it is used as a queue, it is faster than LinkedList.
Useful methods
Method |
Description |
For queue |
For stack |
E remove() |
It removes and returns the next element or throws an exception if an 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 the next element or returns null if empty queue. |
Yes |
No |
E peek() |
It returns the next element or returns null if empty queue. |
Yes |
Yes |
E pop() |
It removes and returns the next element or throws an exception if an 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 the next element or throws an exception if an 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:
import java.util.ArrayDeque; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new ArrayDeque<>(); System.out.println(q.offer(6)); // true System.out.println(q.offer(4)); // true System.out.println(q.peek()); // 6 System.out.println(q.poll()); // 6 System.out.println(q.poll()); // 4 System.out.println(q.peek()); // null } }
Output:
true true 6 6 4 null