LinkedList as a FIFO Queue
suggest changeThe java.util.LinkedList class implements java.util.List and is also a general-purpose implementation of the java.util.Queue interface, 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.
Queue<String> queue = new LinkedList<String>();
queue.offer( "first element" );
queue.offer( "second element" );
queue.offer( "third element" );
queue.offer( "fourth element" );
queue.offer( "fifth element" );
while ( !queue.isEmpty() ) {
System.out.println( queue.poll() );
}
The output of this code is
first element
second element
third element
fourth element
fifth element
As seen in the output, the first inserted element “first element” is removed first, “second element” is removed in the second place, and so on.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents