Potential bug in Java Stack class and its workaround
In this post, we would like to point out a bug in Java Stack class that causes stack elements to be printed in FIFO order instead of the expected LILO order.
There is a potential bug in the Java Stack class that affects the way it iterates through its elements. The iterator() method on java.util.Stack iterates through a stack in a bottom-up manner, giving a false impression as if it were popping off the top of the Stack. This is contrary to the expected behavior of a stack data structure, which is a last-in, first-out (LIFO) data structure. For example, consider the following code. The output will be [1, 2, 3] (FIFO order) instead of [3, 2, 1] (LIFO order).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Iterator; import java.util.Stack; class Main { public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.push(1); stack.push(2); stack.push(3); // using iterator to iterate through a stack Iterator<Integer> itr = stack.iterator(); // `hasNext()` returns true if the stack has more elements while (itr.hasNext()) { // `next()` returns the next element in the iteration System.out.println(itr.next()); } } } |
This bug was reported to the Java Bug Database. They accepted that it was a bad design decision to have Stack extend Vector (“is-a” rather than “has-a”), but it was not fixed because of backward compatibility issues. One workaround for this problem is to use the Deque interface instead of the Stack class. All Deque implementations (ArrayDeque, LinkedList, etc.) uses double ended queue, which provides a more complete and consistent set of LIFO and FIFO operations, and its iterator() method iterates through the stack from top to bottom. For instance:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; class Main { public static void main(String[] args) { Deque<Integer> stack = new ArrayDeque<Integer>(); stack.push(1); stack.push(2); stack.push(3); Iterator<Integer> itr = stack.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); // prints [3, 2, 1] } } } |
Please note that if the stack is modified during the loop, then ConcurrentModificationException is thrown by the iterator. That’s all about bug in Java Stack class and its workaround.
Suggested Read:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)