Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Deque Stack Queue


In Java Deque can be used as LIFO Queue, which is a Stack. In this Java tutorial we’ll explain how it works and show how to use JDK API effectively!


Standard java.util.Deque is a LILO (Last In, Last Out) structure, which means that items added as last, will be removed as last. Contrary to that is LIFO (Last In, First Out), which means that item added as last will be removed as the first, so it’s a Stack.

In JDK there is a java.util.Stack class, but it should not be used because it extends a java.util.Vector, which is a list and lists are not LIFO, but LILO. And anyone can pass it as a Vector to methods that will operate on it as on any other Vector. Uncool. :-|

The following example illustrates how to turn LinkedList, which is an implementation of Deque into a Stack:


import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class CollectionsAsLifoQueue {

    public static void main(String[] args) {
        // Deque is LILO (Last In Last Out)
        Deque<String> items = new LinkedList<>();

        // In this Deque items are added at the end:
        System.out.println("Added to Deque: " + items);

        // In this Deque items are removed from the front:
        System.out.println("Removed from Deque: " + items);

        // View this Deque as a LIFO Queue, which is a Stack
        Queue<String> stack = Collections.asLifoQueue(items);

        // In Stack items are added at the front:
        System.out.println("Added to Stack: " + items);

        // And removed from the front:
        System.out.println("Removed from Stack: " + items);

In the example you can see that LinkedList is a Deque and we (re)use java.util.Collections.asLifoQueue() method to view the list as a LIFO Queue, which is… a Stack!

Running the Deque as Stack example will print the following output:

Added to Deque: [a, b]
Removed from Deque: [b]
Added to Stack: [c, b]
Removed from Stack: [b]

Look at the order in which items are added removed from the structure. In case of Deque we have LILO, but when we use it as a Stack (LIFO Queue), it behaves as LIFO!

As usually, we’ve applied Item 47 from “Effective Java, 2nd” – Know and use the libraries! ;-)

Share with the World!