Being a Queue subtype all methods in the Queue and Collection interfaces are also available in the Dequeinterface.Since Deque is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Deque implementations in the Java Collections API:
LinkedList is a pretty standard deque / queue implementation.ArrayDeque stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the ArrayDeque grows as needed, even if it stores its elements in an array.
There are also Queue implementations in the java.util.concurrent package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a Deque instance:
To add elements to the tail of a Deque, you call its add() method. You can also use the addFirst() andaddLast() methods, which add elements to the head and tail of the deque.
The order in which the elements added to the Deque are stored internally, depends on the implementation. The two implementations mentioned earlier both store the elements in the order (first or last) in which they are inserted.
You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the element() method. You can also use the getFirst and getLast() methods, which return the first and last element in the Deque. Here is how that looks:
To remove elements from a deque, you call the remove(), removeFirst() and removeLast methods. Here are a few examples: