The java.util.LinkedList class, while implementing java.util.List is a general-purpose implementation of java.util.Queue interface too operating on a FIFO (First In, First Out) principle.
In the example below, with offer() method, the elements are inserted into the LinkedList. This insertion operation is called enqueue. In the while loop below, the elements are removed from the Queue based on FIFO. This operation is called dequeue.
import java.util.*; public class QueueExample { public static void main(String[] args) { Queue<String> newQueue = new LinkedList<>(); newQueue.offer("apple"); newQueue.offer("banana"); newQueue.offer("orange"); newQueue.offer("grape"); newQueue.offer("melon"); while (!newQueue.isEmpty()) { System.out.println(newQueue.poll()); } } }
Output
apple banana orange grape melon
As seen in the output, the first inserted element "first element" is removed firstly, "second element" is removed in the second place etc
Basics
A Queue is a collection for holding elements prior to processing. Queues typically, but not necessarily, order elements in a FIFO (first-in-first-out) manner.
Head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue.
The Queue Interface
public interface Queue<E> extends Collection<E> { boolean add(E e); boolean offer(E e); E remove(); E poll(); E element(); E peek(); }
Each Queue method exists in two forms:
Type of Operation | Throws Exception | Returns Special Value |
---|---|---|
Insert | add(e) | offer(e) |
Remove | remove() | poll() |
Examine | element() | peek() |
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions