A queue is a collection of objects on which operations can only be performed at two ends of the queue.
A queue has two ends known as head and tail.
In the simple queue, objects are added to the tail and removed from the head and the object added first will be removed first.
Java Collections Framework supports the following types of queues.
Simple queues are represented by an instance of the Queue
interface.
A queue lets you perform three basic operations:
The Queue interface defines two methods for each of the three operations. One method throws an exception if the operation is not possible and the other method returns a false or null to indicate the failure.
Method | Description |
---|---|
boolean add(E e) | Adds an element to the queue if it is possible. Otherwise, it throws an exception. |
boolean offer(E e) | Adds an element to the queue without throwing an exception if the element cannot not be added. It returns false on failure and true on success. |
E remove() | removes the head of the queue. It throws an exception if the queue is empty. This method returns the removed item. |
E poll() | remove element from a Queue. it returns null if the queue is empty instead of throwing an exception. |
E element() | Peek the head of the queue without removing it from the queue. It throws an exception if the queue is empty. |
E peek() | Peek the queue and it returns null if the queue is empty instead of throwing an exception. |
The LinkedList and PriorityQueue are two implementation classes for the Queue interface. LinkedList also implement the List interface.
The following code shows how to use a LinkedList as a FIFO queue.
import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; //from w w w . ja v a2 s.co m public class Main { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); queue.add("Java"); // offer() will work the same as add() queue.offer("SQL"); queue.offer("CSS"); queue.offer("XML"); System.out.println("Queue: " + queue); // Let's remove elements until the queue is empty while (queue.peek() != null) { System.out.println("Head Element: " + queue.peek()); queue.remove(); System.out.println("Removed one element from Queue"); System.out.println("Queue: " + queue); } System.out.println("queue.isEmpty(): " + queue.isEmpty()); System.out.println("queue.peek(): " + queue.peek()); System.out.println("queue.poll(): " + queue.poll()); try { String str = queue.element(); System.out.println("queue.element(): " + str); str = queue.remove(); System.out.println("queue.remove(): " + str); } catch (NoSuchElementException e) { System.out.println("queue.remove(): Queue is empty."); } } }
The code above generates the following result.