Search code examples
javafor-loopstack

Why can't I loop over a Stack using a for loop?


I have a Stack with 3 items and I want to loop over each item. If I do this:

public class Main {
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>();
        s.add(1);
        s.add(2);
        s.add(3);
    
        for (Integer num = s.pop(); !s.isEmpty(); num = s.pop()) {
            System.out.println(num);
        }
    }
}

then it only prints out 3 and 2 but not 1. Why is that?


Solution

  • The for loop pops the stack then exits the loop if the stack is empty.

    for (Integer num = s.pop(); !s.isEmpty(); num = s.pop()) {
        System.out.println(num);
    }
    

    Put another way, num = s.pop() is run before the test !s.isEmpty(). So on the final iteration, the stack is empty, therefore the loop body isn't executed.

    There are many different ways around this. One thing you could do is use a while loop instead:

    while (!s.isEmpty()) {
        System.out.println(s.pop());
    }