Java queue Queue usage example in detail

  • 2020-06-23 00:32:04
  • OfStack

Queues are a special kind of linear table that allows only delete operations at the front of the table and inserts at the back of the table.

The LinkedList class implements the Queue interface, so we can use LinkedList as Queue.

The following example demonstrates the use of queues (Queue) :


/*
 author by w3cschool.cc
 Main.java
 */
import java.util.LinkedList;
import java.util.Queue;
public class Main {
 public static void main(String[] args) {
  //add() and remove() Method throws an exception when it fails ( Is not recommended )
  Queue<String> queue = new LinkedList<String>();
  // Add elements 
  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()); // Returns the first 1 Element, and delete it from the queue 
  for(String q : queue){
   System.out.println(q);
  }
  System.out.println("===");
  System.out.println("element="+queue.element()); // Returns the first 1 An element  
  for(String q : queue){
   System.out.println(q);
  }
  System.out.println("===");
  System.out.println("peek="+queue.peek()); // Returns the first 1 An element  
  for(String q : queue){
   System.out.println(q);
  }
 }
}

The output result of the above code operation is:


a
b
c
d
e
===
poll=a
b
c
d
e
===
element=b
b
c
d
e
===
peek=b
b
c
d
e

I hope you found this queue instance helpful


Related articles: