Java Example - Queue Usage
A queue is a special linear list that only allows deletion operations at the front of the list and insertion operations at the back of the list.
The LinkedList class implements the Queue interface, so we can use LinkedList as a Queue.
The following example demonstrates the usage of a Queue:
Main.java file
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
//The add() and remove() methods throw an exception when they fail (not recommended)
Queue<String> queue = new LinkedList<String>();
//Add element
queue.offer("a");
queue.offer("b");
queue.offer("c");
queue.offer("d");
queue.offer("e");
for(String q : queue){
System.out.println(q);
}
System.out.println("===");
System.out.println("poll="+queue.poll()); //Return the first element and remove it from the queue
for(String q : queue){
System.out.println(q);
}
System.out.println("===");
System.out.println("element="+queue.element()); //Return the first element
for(String q : queue){
System.out.println(q);
}
System.out.println("===");
System.out.println("peek="+queue.peek()); //Return the first element
for(String q : queue){
System.out.println(q);
}
}
}
The output of running the above code is:
a b c d e === poll=a b c d e === element=b b c d e === peek=b b c d eOther Extensions
Java Example