Don't take anything for granted - iterating over a java.util.Stack

Don’t ever think just because a certain way of doing things seems reasonable or logical to you or anyone else means it’s implemented that way.

In computer science, a stack is a last in, first out (LIFO) abstract data type and linear data structure.

from wikipedia

The key characteristic here is “last in, first out”. So, when I do something like this:

1
2
3
4
5
Stack<String> myStack = new Stack<>();
myStack.push("a");
myStack.push("b");
myStack.push("c");
myStack.push("d");

and then “go through” the stack and print every item, I’d expect something very much like dcba as the result, pretty much like what I get doing this:

1
2
3
while (!myStack.empty()) {
    System.out.print(myStack.pop());
}

But completely different from what I get doing this:

1
2
3
for (String item: myStack) {
    System.out.print(item);
}

This prints abcd, which is definitely surprising, at least to me and it’s so surprising that it fools me every time I use this class. A stack a such should offer two functions, push and pop and maybe a peek-method as well. It’s meant to store data and return it in reverse order while destroying itself. I’m not sure if I’d expect the foreach to destroy my stack but I’ pretty sure, this shouldn’t implement a hidden reverse or invert method.