The Java Doc says that a Stack
should preferably be created from a Deque
, rather than using the quintessential Stack<>
. Unfortunately, it does not emphasize why so.
Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class. When a deque is used as a stack, elements are pushed and popped from the beginning of the deque.
Could someone please point out why so? Similarly, are there other instances wherein we should avoid using the inbuilt Collections
objects? I am a C++ developer moving onto Java, hence any such subtle pointers would be helpful.
Thanks.
Java generics were added after initial implementations of collections; Stack
is from Java 1.0 - and rather then break existing code when they added generics, it was decided to add classes that duplicate functionality (but provide a consistent API). That is why you should prefer a Deque
- it provides an API consistent with all of the other Java Collection
s.