Home  Dsa   How to use ...

How to use ArrayDeque as a stack in Java

Let us see how to use a Deque strictly as a stack and prevent anyone from removing elements from the bottom. Let’s go through the options.


1️⃣ Use only stack methods

The cleanest way is to only expose these methods to the rest of your code:

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

class StackWrapper<T> {
    private Deque<T> stack = new ArrayDeque<>();

    public void push(T item) {
        stack.push(item); // adds to top
    }

    public T pop() {
        return stack.pop(); // removes from top
    }

    public T peek() {
        return stack.peek(); // looks at top
    }

    public boolean isEmpty() {
        return stack.isEmpty();
    }
}

✅ This encapsulates the Deque, so no one can call removeLast() from outside.


2️⃣ Do not expose Deque directly


3️⃣ Optional: Throw exception if bottom is accessed

If you must expose the Deque, you could override/remove bottom operations in a subclass or wrapper:

class SafeStack<T> extends ArrayDeque<T> {
    @Override
    public T removeLast() {
        throw new UnsupportedOperationException("Cannot remove from bottom!");
    }
}

✅ Summary


Published on: Oct 08, 2025, 07:18 AM  
 

Comments

Add your comment