简体   繁体   English

为什么Java.Util.Stack没有弹出循环中的最后一个元素?

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

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-> 3-> 2->

And Not 并不是

3->2->1 3-> 2-> 1

Shouldn't the loop run thrice , Is the condition i < s.size() changing as the stack size changes ? 循环不应该运行三次,条件i < s.size()随堆栈大小的变化而变化?

Is the condition i < s.size() changing as the stack size changes ? 条件i < s.size()随堆栈大小的变化而变化?

Yes, because i increases while at the same time size() decreases. 是的,因为i增加了同时size()减少了。 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();
    ...
}

Yes, just like you said, the loop checks the value of i against the stack size. 是的,就像你说的那样,循环根据堆栈大小检查i的值。 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(" ->");
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM