I've been wondering for a while why an ArrayList
does not have a stack-like interface (think push()
and pop()
)
I frequently find myself using these constructs in Java:
list.get(list.size() - 1);
list.remove(list.size() -1);
While I rather do something like:
list.peek();
list.pop();
I know the legacy class Stack
exists, which clashes with a potential interface called Stack
, but that wouldn't stop them from making a stack-like interface with a different name.
A Deque
also exists, but it can not be (efficiently) backed by an array-like collection for obvious reasons. One downside is that it's implementations are often linked-list-like and therefore don't support random access. There are situations where random-access in a stack is desired, like in Reverse Polish notation calculations or in emulators (implementing an actual call stack)
I also know that the ArrayDeque
class exists, which is almost a copy of ArrayList
(why?) and explicitly warns about inefficient deque-operations that operate on the first element or elements in the middle. It's also yet another class to learn, possibly with it's own quirks that differ from ArrayList
. Why was this route chosen instead of adding the Deque
interface to ArrayList
? (Is it to prevent inexperienced programmers from making unobvious (performance-related) mistakes?)