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
- Avoid giving direct access to the
Dequeobject. - If you pass the Deque reference to other code, someone can still call
removeLast().
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!");
}
}
- Any call to
removeLast()will now throw an exception.
✅ Summary
- Best practice: Wrap the
Dequein a class and only exposepush,pop,peek - Don’t let external code see the Deque reference
- Optional: override/remove bottom methods if needed
Published on: Oct 08, 2025, 07:18 AM