Java SE: How to iterate Stack 博客分类: JavaSE JavaStackIterate
程序员文章站
2024-03-09 11:17:53
...
How to iterate a stack in Java?
1> Pitfall: Using iterator to iterate Stack
@Test public void iterateTest() { Stack<String> stack = new Stack<String>(); stack.push("I"); stack.push("Love"); stack.push("You"); for (String str : stack) { System.out.println(str); } } // Output: I Love You
Contrary to our expectation, It is iterated like a Queue instead of a Stack.
It's a bug listed in BugList matained by Oracle and won't be fixed because of capatibility.
2> The correct way to iterate stack is:
@Test public void iterateTest2() { Stack<String> stack = new Stack<String>(); stack.push("I"); stack.push("Love"); stack.push("You"); while (!stack.isEmpty()) { System.out.println(stack.pop()); } } //Output: You Love I
Reference Links:
1) http://www.tigraine.at/2010/05/12/never-assume-stack-iterators-in-java
2) http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4475301