Deque
Published Aug 9, 2024
Contribute to Docs
A Deque extends the Queue
interface and is a double-ended queue. It provides methods to add, access, and remove items at the top and end of the deque. Thereby, it can be used as a queue or stack. The Deque
interface is included in the java.util
package.
Syntax
import java.util.deque;
Deque<DataType> myDeque = new DequeClass<DataType>();
Where DataType
is the data type to be stored in the deque, and DequeClass
is a class implementing the Deque
interface, for example, ArrayDeque
or LinkedList
.
Example
The following is an example of the Deque
interface implemented by an ArrayDeque
:
import java.util.Deque;import java.util.ArrayDeque;public class Main {public static void main(String[] args) {Deque<String> food = new ArrayDeque<String>();food.addFirst("Cabbage");food.addLast("Sausage");food.addFirst("Potatoes");food.addLast("Salad");System.out.println(food);System.out.println(food.pollFirst());System.out.println(food.peekFirst());System.out.println(food);}}
The above example results in the following output:
[Potatoes, Cabbage, Sausage, Salad]PotatoesCabbage[Cabbage, Sausage, Salad]
Methods
The following list contains a selection of methods provided by the Deque
interface:
.addFirst(item)
: Addsitem
at the top of theDeque
if possible, otherwise it throws an exception..addLast(item)
: Addsitem
at the end of theDeque
if possible, otherwise it throws an exception..getFirst()
: Returns, without removal, the first item of theDeque
. It throws an exception if the Deque is empty..offerLast(item)
: Addsitem
at the end of theDeque
if possible, otherwise it returnsfalse
..peekFirst()
: Returns, without removal, the first element of theDeque
. Returnsnull
if theDeque
is empty..pollFirst()
: Returns and removes the first item of theDeque
. Returnsnull
if theDeque
is empty..removeFirst()
: Returns and removes the first item of theDeque
. Throws an exception if theDeque
is empty.
Equivalent methods Stack and Queue
The following table lists the equivalent methods for Queue
and Stack
:
Deque method |
Equivalent Queue method |
Equivalent Stack method |
---|---|---|
.addFirst(item) |
- | .push(item) |
.addLast(item) |
.add(item) |
- |
.getFirst() |
.element() |
- |
.offerLast(item) |
.offer(item) |
- |
.peekFirst() |
.peek() |
.peek() |
.pollFirst() |
.poll() |
- |
.removeFirst() |
.remove() |
.pop() |
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours