Why use Deque over Stack in Java

From JavaDoc for Stack, we could see:

"A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. For example:"

Deque<Integer> stack = new ArrayDeque<>();

Here are some answers from Why should I use Deque over Stack?.

  1. Inconsistency: Stack extends the Vector class, which allows you to access element by index. This is inconsistent with what a Stack should actually do, which is why the Deque interface is preferred (it does not allow such operations)–its allowed operations are consistent with what a FIFO or LIFO data structure should allow.

  2. Stack has no interface, so if you know you need Stack operations you end up committing to a specific concrete class, which isn’t usually a good idea.

  3. Also as pointed out in the comments, Stack and Deque have reverse iteration orders:

    // for stack
    Stack<Integer> stack = new Stack<>();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    System.out.println(new ArrayList<>(stack)); // prints 1, 2, 3
    // for deque
    Deque<Integer> deque = new ArrayDeque<>();
    deque.push(1);
    deque.push(2);
    deque.push(3);
    System.out.println(new ArrayList<>(deque)); // prints 3, 2, 1
  4. Performance: The Vector class that Stack extends is basically the "thread-safe" version of an ArrayList. The synchronizations can potentially cause a significant performance hit to your application.

Leave a Reply