JDK-8345280 : java.util.Stack iterator not iterating from top of stack
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 17
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2024-12-01
  • Updated: 2024-12-02
  • Resolved: 2024-12-02
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE PROBLEM :
// stack iterator starts from bottom of stack instead of top of stack
import java.util.Stack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Main {
    public static void main(String[] args) {
        Stack<Character> stack = new Stack<>();
        Collection<Character> list = new ArrayList<>();
        stack.push('a');
        list.add('b');
        stack.addAll(list);
        Iterator stackIterator = stack.iterator();
        // prints 'a' (bottom of stack) and not 'b' (top of stack)
        System.out.println(stackIterator.next());
        // prints 'b' (top of stack) and not 'a' (bottom of stack)
        System.out.println(stackIterator.next());
    }
}



Comments
As of JDK 21 with Sequenced Collections it's possible to call reversed() on the Stack to obtain a reversed view, which can be iterated in the opposite direction.
02-12-2024

The iterator method in Stack is inherited from Vector and simply iterates through its elements in insert order. Use an implementation of the Deque interface, e.g. ArrayDeque, which implements stack and queue functionality at the same time for fully-functional stack. Closed as not an issue.
02-12-2024