A Deque
is a "double ended queue" which means that a elements can be added at the front or the tail of the queue. The queue only can add elements to the tail of a queue.
The Deque
inherits the Queue
interface which means the regular methods remain, however the Deque interface offers additional methods to be more flexible with a queue. The additional methods really speak for them self if you know how a queue works, since those methods are intended to add more flexibility:
Method | Brief description |
---|---|
getFirst() | Gets the first item of the head of the queue without removing it. |
getLast() | Gets the first item of the tail of the queue without removing it. |
addFirst(E e) | Adds an item to the head of the queue |
addLast(E e) | Adds an item to the tail of the queue |
removeFirst() | Removes the first item at the head of the queue |
removeLast() | Removes the first item at the tail of the queue |
Of course the same options for offer
, poll
and peek
are available, however they do not work with exceptions but rather with special values. There is no point in showing what they do here.
To add elements to the tail of a Deque you call its add()
method. You can also use the addFirst()
and addLast()
methods, which add elements to the head and tail of the deque.
Deque<String> dequeA = new LinkedList<>();
dequeA.add("element 1"); //add element at tail
dequeA.addFirst("element 2"); //add element at head
dequeA.addLast("element 3"); //add element at tail
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:
String firstElement0 = dequeA.element();
String firstElement1 = dequeA.getFirst();
String lastElement = dequeA.getLast();
To remove elements from a deque, you call the remove()
, removeFirst()
and removeLast()
methods. Here are a few examples:
String firstElement = dequeA.remove();
String firstElement = dequeA.removeFirst();
String lastElement = dequeA.removeLast();