Why does the Java.Util.Stack not pop last element in the loop?

1.1k views Asked by At

I have a very Basic Question

Stack<Integer> s=new Stack<integer>();
s.push(New Integer(1));
s.push(New Integer(2));
s.push(New Integer(3));
for(int i=0;i<s.size();i++){
                System.out.println("i: "+i+" size:"+s.size());
                System.out.print(s.pop());
                if(s.size()>=1)
                    System.out.print(" ->");
 }

This results in an output of

3->2->

And Not

3->2->1

Shouldn't the loop run thrice , Is the condition i < s.size() changing as the stack size changes ?

2

There are 2 answers

1
Radiodef On BEST ANSWER

Is the condition i < s.size() changing as the stack size changes ?

Yes, because i increases while at the same time size() decreases. Walk through the logic in your head or on paper.

for ( i = 0, size = 3 )
    pop() ... i++

for ( i = 1, size = 2 )
    pop() ... i++

for ( i = 2, size = 1 )
    loop ends

We would normally write such a loop like this:

while (!s.isEmpty()) {
    Integer e = s.pop();
    ...
}
0
JShell On

Yes, just like you said, the loop checks the value of i against the stack size. Since the stack size is changing, it doesn't do what you want it do. Just put the initial stack size into a variable:

Stack<Integer> s=new Stack<integer>();
s.push(New Integer(1));
s.push(New Integer(2));
s.push(New Integer(3));
int size = s.size()
for(int i=0;i<size;i++){
                System.out.println("i: "+i+" size:"+s.size());
                System.out.print(s.pop());
                if(s.size()>=1)
                    System.out.print(" ->");
 }