Re: foreach and stack, iterating from the bottom-up?
On May 5, 10:25 am, WP <mindcoo...@gmail.com> wrote:
Hello, I just tried a foreach loop with a Stack (Stack<String> to be
precise) and I was a bit surprised that it seems to iterate from the
bottom up. I thought it would go from the top down because, with
stacks, you usually have to remove what's on the top to get to the
bottom. Note that I didn't want to empty the stack itself, just
iterate over it. Why was it implemented this way? It's not an actual
problem, I simply adapted my logic in the method to this behavior,
but, as I said, I was surprised.
- WP
java.util.Stack is implemented by extending Vector, which is an auto-
resizing (and synchronizing) wrapper over an array. For efficiency,
stack items are added to and removed from the end of the array; the
iteration order as inherited from Vector is from the beginning of the
array.
Note this snippet in the documentation of Stack:
Sun wrote:
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<Integer>();
Using a Deque as your stack gives you more control over which order
iteration goes in: if you push and pop at the front of a deque, then
iteration over it will proceed from the top of the stack down; if you
push and pop at the back, then iteration will proceed from the bottom
up.
The Stack, Vector, Hashtable, and Enumeration classes have been
superseded by the Collections framework. Aside from Java 1
compatibility, there are no good reasons to use these classes in new
code.
-o