The Queue
interface in the Java Collections Framework represents a collection of elements that supports insertion and removal operations. It follows the first-in, first-out (FIFO) principle, where the element that is added first is also the first one to be removed.
One of the implementations of the Queue
interface is the LinkedList
class. It provides efficient operations for adding elements to the end of the queue (enqueue
or add
) and removing elements from the front of the queue (dequeue
or poll
).
Here's an example of using the Queue
interface with the LinkedList
class:
1// Create a Queue using LinkedList
2Queue<String> queue = new LinkedList<>();
3
4// Enqueue elements
5queue.add("John");
6queue.add("Alice");
7queue.add("Bob");
8
9// Dequeue elements
10String firstElement = queue.poll();
11String secondElement = queue.poll();
12
13// Print the dequeued elements
14class Main {
15 public static void main(String[] args) {
16 System.out.println(firstElement); // Output: John
17 System.out.println(secondElement); // Output: Alice
18 }
19}
In the above code, we create a Queue
using the LinkedList
class and add elements (John
, Alice
, and Bob
) to the queue. We then dequeue the elements using the poll
method and print the dequeued elements (John
and Alice
).
The Queue
interface and the LinkedList
class are commonly used in various scenarios, such as task scheduling, message passing, and event handling, where the order of elements is important.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Create a Queue using LinkedList
Queue<String> queue = new LinkedList<>();
// Enqueue elements
queue.add("John");
queue.add("Alice");
queue.add("Bob");
// Dequeue elements
String firstElement = queue.poll();
String secondElement = queue.poll();
// Print the dequeued elements
System.out.println(firstElement); // Output: John
System.out.println(secondElement); // Output: Alice
}
}