Potential Bug in Stack Class and a Workaround

In this post, we would like to point out a bug in Stack Class that causes stack elements to be printed in FIFO order instead of expected LILO order.


The iterator() method on java.util.Stack iterates through a stack in bottom-up manner and giving a false impression as if it were popping off the top of the Stack.

For example, consider below code. The output will be [1, 2, 3] (FIFO order) instead of [3, 2, 1] (LIFO order).


Download   Run Code

This bug was also reported to the Java Bug Database. They accepted that it was bad design decision to have Stack extend Vector (“is-a” rather than “has-a”) but unfortunately they can’t fix this issue because of backward compatibility.

One workaround to this problem is to use Deque interface. All Deque implementations like ArrayDeque, LinkedList, etc uses “double ended queue” which provides more complete and consistent set of LIFO and FIFO operations. For example, iterator() method on Deque iterates through the stack from top to bottom –


Download   Run Code

Please note that if stack is modified during the loop, then ConcurrentModificationException is thrown by the iterator.

Suggested Read: Iterate over Deque in Java (Forward and Backward directions)

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of