I need a Stack data structure for my use case. I should be able to push items into the data structure and I only want to retrieve the last item from the Stack. The JavaDoc for Stack says :
A more complete and consistent set of LIFO stack operations is
provided by the Deque interface and its implementations, which should
be used in preference to this class. For example:
Deque<Integer> stack = new ArrayDeque<>();
I definitely do not want synchronized behavior here as I will be using this datastructure local to a method . Apart from this why should I prefer Deque over Stack here ?
P.S: The javadoc from Deque says :
Deques can also be used as LIFO (Last-In-First-Out) stacks. This
interface should be used in preference to the legacy Stack class.
For one thing, it’s more sensible in terms of inheritance. The fact that
StackextendsVectoris really strange, in my view. Early in Java, inheritance was overused IMO –Propertiesbeing another example.For me, the crucial word in the docs you quoted is consistent.
Dequeexposes a set of operations which is all about being able to fetch/add/remove items from the start or end of a collection, iterate etc – and that’s it. There’s deliberately no way to access an element by position, whichStackexposes because it’s a subclass ofVector.Oh, and also
Stackhas no interface, so if you know you needStackoperations you end up committing to a specific concrete class, which isn’t usually a good idea.Also as pointed out in the comments,
StackandDequehave reverse iteration orders:which is also explained in the JavaDocs for Deque.iterator():