Never assume! Stack iterators in Java
May 12, 2010 by Daniel HoelblingI spent almost 2 hours of debugging Java code yesterday due to one assumption that proved fatally wrong: I assumed a Stack, by definition a LIFO data structure would iterate over it’s elements from the top of the stack to the bottom.
So inserting 1, 2, 3 the resulting order when iterating through the stack should be 3, 2, 1.
Well, at least that’s what .NET does. Java is different. Look at the following Java code:
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
for(Integer i : stack) {
System.out.println(i);
}
And this C#:
var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
foreach (var i in stack)
{
Console.WriteLine(i);
}
Well, they look exactly the same, but Java will return 1,2,3 while C# will honor the Stack’s special semantics and return 3,2,1. Great stuff isn’t it?
The workaround was quite simple, yet it had cost me 2 hours of my life trying to hunt a bug in my code, never thinking the bug could lie in a simple foreach iteration through the stack..
Lesson learned: Never assume you know anything about data structure semantics unless you have checked that your assumptions are indeed true. Implementations differ and sometimes this will bite you.
Oh and did I mention that the way Java does it is simply wrong?