Java provides a Queue interface which is part of Java’s collections framework. A Queue in Java is just an interface. We need a concrete implementation of the Queue interface to work with, in our programs. The LinkedList class implements the Queue interface and therefore it can be used as a Queue.
Creating a Queue and Performing basic operations like Enqueue and Dequeue:
Creating a Queue and Performing basic operations like Enqueue and Dequeue:
import java.util.LinkedList;
import java.util.Queue;
/**
* Demonstrate Queue interface methods with LinkedList implementation.
* @author javaguides.net
*
*/
public class QueueExample {
public static void main(String[] args) {
// Create and initialize a Queue using a LinkedList
Queue<String> elementQueue = new LinkedList<>();
// Adding new elements to the Queue (The Enqueue operation)
elementQueue.add("element1");
elementQueue.add("element2");
elementQueue.add("element3");
elementQueue.add("element4");
System.out.println("WaitingQueue : " + elementQueue);
// Removing an element from the Queue using remove() (The Dequeue operation)
// The remove() method throws NoSuchElementException if the Queue is empty
String name = elementQueue.remove();
System.out.println("Removed from WaitingQueue : " + name + " | New WaitingQueue : " + elementQueue);
// Removing an element from the Queue using poll()
// The poll() method is similar to remove() except that it returns null if the Queue is empty.
name = elementQueue.poll();
System.out.println("Removed from WaitingQueue : " + name + " | New WaitingQueue : " + elementQueue);
}
}
Output:
WaitingQueue : [element1, element2, element3, element4]
Removed from WaitingQueue : element1 | New WaitingQueue : [element2, element3, element4]
Removed from WaitingQueue : element2 | New WaitingQueue : [element3, element4]
Comments
Post a Comment