Deque

suggest change

A Deque is a double-ended queue: elements can be added or removed at the head or at the tail. A plain Queue adds only at the tail and removes only at the head.

Deque extends Queue, so the queue methods remain. It also adds methods that name the end they use:

Method Brief description
getFirst() Returns the head element without removing it.
getLast() Returns the tail element without removing it.
addFirst(E e) Inserts at the head.
addLast(E e) Inserts at the tail.
removeFirst() Removes and returns the head.
removeLast() Removes and returns the tail.

offerFirst, offerLast, pollFirst, pollLast, peekFirst, and peekLast are the same operations, but they return false or null instead of throwing.

Adding and Accessing Elements

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();

Removing Elements

To remove elements from a deque, you call the remove(), removeFirst() and removeLast() methods. Here are a few examples:

String removed = dequeA.remove();
String removedHead = dequeA.removeFirst();
String lastElement  = dequeA.removeLast();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents