The Deque
interface in the Java Collections Framework represents a double-ended queue, which allows elements to be inserted and removed from both ends. It extends the Queue
interface and provides additional methods for adding and removing elements from both the beginning and the end of the deque.
One of the implementations of the Deque
interface is the ArrayDeque
class. It internally uses an array to store the elements and provides constant-time operations for adding and removing elements from both ends.
Here's an example of using the Deque
interface with the ArrayDeque
class:
1// Create a Deque using ArrayDeque
2Deque<Integer> deque = new ArrayDeque<>();
3
4// Add elements
5deque.addFirst(1);
6deque.addLast(2);
7deque.addFirst(3);
8
9System.out.println(deque); // Output: [3, 1, 2]
10
11// Retrieve elements
12int firstElement = deque.peekFirst();
13int lastElement = deque.peekLast();
14
15System.out.println(firstElement); // Output: 3
16System.out.println(lastElement); // Output: 2
17
18// Remove elements
19deque.removeFirst();
20
21System.out.println(deque); // Output: [1, 2]
22
23deque.removeLast();
24
25System.out.println(deque); // Output: [1]
In the above code, we create a Deque
using the ArrayDeque
class and add elements (1, 2, and 3) to the deque. We then retrieve the first and last elements using the peekFirst
and peekLast
methods. Finally, we remove the first and last elements using the removeFirst
and removeLast
methods.
The Deque
interface and the ArrayDeque
class are commonly used in various scenarios, such as implementing stacks, queues, and breadth-first search algorithms. Their constant-time operations for adding and removing elements from both ends make them efficient choices for such use cases.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Replace with your Java logic here
Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(1);
deque.addLast(2);
deque.addFirst(3);
System.out.println(deque); // Output: [3, 1, 2]
int firstElement = deque.peekFirst();
int lastElement = deque.peekLast();
System.out.println(firstElement); // Output: 3
System.out.println(lastElement); // Output: 2
deque.removeFirst();
System.out.println(deque); // Output: [1, 2]
deque.removeLast();
System.out.println(deque); // Output: [1]
}
}