Wither Well
Wither Well
JCHJava Community | Help. Code. Learn.
Created by Wither Well on 3/29/2025 in #java-help
Stack Interface, Deque Implementation: Worth it?
First time poster here, so please be lenient :) I have learned that the Stack class in Java inherits Vector class, which breaks LIFO contract. I also learned that Deque (a double-ended queue, seems contradictory) does not strictly maintain LIFO contract and is not thread-safe as far as I know (though this can be solved with ConcurrentLinkedDeque). Anyway, I have found a solution being: Defining a Stack interface
public interface Stack<E> {
void push(E item);
E pop();
E peek();
boolean isEmpty();
}
public interface Stack<E> {
void push(E item);
E pop();
E peek();
boolean isEmpty();
}
Defining a DequeStack class implementing Stack
public class DequeStack<E> implements Stack<E> {
private final Deque<E> deque = new ArrayDeque<E>();

@Override
public void push(E item) {
deque.addFirst(item);
}

@Override
public E pop() {
return deque.removeFirst();
}

@Override
public E peek() {
return deque.peekFirst();
}

@Override
public boolean isEmpty() {
return deque.isEmpty();
}
}
public class DequeStack<E> implements Stack<E> {
private final Deque<E> deque = new ArrayDeque<E>();

@Override
public void push(E item) {
deque.addFirst(item);
}

@Override
public E pop() {
return deque.removeFirst();
}

@Override
public E peek() {
return deque.peekFirst();
}

@Override
public boolean isEmpty() {
return deque.isEmpty();
}
}
My main issue simply: Is this even worth it? Are there cases where this would be necessary? Perhaps a specific case such as RPN implementation or can one still get away with using Deque? Also, are there potential alternatives to this? Should Stack class still be used as is or should Deque interface be implemented normally (for example, using ArrayDeque)? I tried looking online but most seemed to suggest either using Deque as is or provided the solution above, though nobody seemed to discuss the point/necessity of this.
33 replies