Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Using `Deque` as a LIFO stack: `push`, `pop`, and `isEmpty`

Store changes in a `Deque` and remove the newest one first. Check that the history has an entry before each call to `pop()`.

Version: Java SE 21

Syntax

void push(E e)
E pop()
boolean isEmpty()

if (!history.isEmpty()) {
    int revision = history.pop(); // history is a Deque<Integer>
}

Deque.push/pop/isEmpty refers to three methods you use through Java SE 21's java.util.Deque<E> interface. A deque is a double-ended queue. When you use it as a stack, the front is the top. This gives you LIFO order (last in, first out): the most recently recorded change is removed first, as in an undo history.

push(E e) inserts at the front, just like addFirst(e), and returns no value (void). It does not require an emptiness check. On a capacity-restricted deque, it throws IllegalStateException if there's no room. pop() removes and returns the front element as an E, just like removeFirst(). On an empty deque it throws NoSuchElementException rather than returning null.

isEmpty() is inherited from Collection. It reports true when there are no elements and false otherwise, without modifying the deque. The ! operator negates that result, so while (!history.isEmpty()) checks before each pop() that at least one entry remains.

The example uses ArrayDeque, which rejects null elements and is not thread-safe. Checking and then removing are two separate operations, not one atomic operation. If multiple threads access the same ArrayDeque, use external synchronization.

Examples

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

public class UndoHistory {
    public static void main(String[] args) {
        Deque<Integer> history = new ArrayDeque<>();
        history.push(1);
        history.push(2);

        while (!history.isEmpty()) {
            System.out.println(history.pop());
        }
        System.out.println(history.isEmpty());
    }
}

Result

2
1
true

The change IDs are pushed in the order `1`, `2`. The program prints `2`, then `1`, then `true` because the history is empty.

Related lessons

  • Java · Lesson 22 · Intermediate · Version: 2

Sources