Daniel Hoelbling-Inzko talks about programming

Never assume! Stack iterators in Java

Posted by Daniel Hölbling on May 12, 2010

I 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>();

for(Integer i : stack) { System.out.println(i); }

And this C#:

var stack = new Stack<int>();

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?

Filed under net, programmierung, java
comments powered by Disqus

My Photography business


dynamic css for .NET