Deque

A deque (pronounced deck) is a double-ended queue. Element insertion or removal occurs at its head or tail. Deques can be used as queues or stacks.

Deque<E>, extends Queue, in which the inherited add(E e) method inserts e at the deque's tail.

A linear collection that supports element insertion and removal at both ends.

The twelve methods described above are summarized in the following table:

This interface extends the Queue interface. When a deque is used as a queue, FIFO (First-In-First-Out) behavior results.

Elements are added at the end of the deque and removed from the beginning.

The methods inherited from the Queue interface are precisely equivalent to Deque methods as indicated in the following table:

Queue MethodEquivalent Deque Method
add(e)addLast(e)
offer(e)offerLast(e)
remove()removeFirst()
poll()pollFirst()
element()getFirst()
peek()peekFirst()

Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class.

When a deque is used as a stack, elements are pushed and popped from the beginning of the deque. Stack methods are precisely equivalent to Deque methods as indicated in the table below:

Stack MethodEquivalent Deque Method
push(e)addFirst(e)
pop()removeFirst()
peek()peekFirst()

This interface is a member of the Java Collections Framework.


import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
  public static void main(String args[]) {
    Deque<String> stack = new ArrayDeque<String>();
    Deque<String> queue = new ArrayDeque<String>();

    stack.push("A");
    stack.push("B");
    stack.push("C");
    stack.push("java2s.com");

    while (!stack.isEmpty())
      System.out.print(stack.pop() + " ");

    queue.add("A");
    queue.add("B");
    queue.add("C");
    queue.add("D");
    while (!queue.isEmpty())
      System.out.print(queue.remove() + " ");
  }
}
  

Revised from Open JDK source code

Home 
  Java Book 
    Collection