stack 的foreach迭代

stack底层为数组, foreach和iterator迭代时遍历数组输出,

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * The array buffer into which the components of the vector are
     * stored. The capacity of the vector is the length of this array buffer,
     * and is at least large enough to contain all the vector's elements.
     *
     * <p>Any array elements following the last element in the Vector are null.
     *
     * @serial
     */
    protected Object[] elementData;

  

所以遍历的顺序是从栈低到栈顶, 和 pop的顺序正好相反

@Test
    public void t () {
        Stack<Integer> s = new Stack<Integer>();
        System.out.println("输入");
        s.push(1);
        System.out.println("1");
        s.push(2);
        System.out.println("2");
        s.push(3);
        System.out.println("3");
        
        System.out.println("foreach");
        for(int i : s){
          System.out.println(i);
        }
        
        System.out.println("Iterator");
        Iterator<Integer> t = s.iterator();
        while(t.hasNext()){
          int i = t.next();
          System.out.println(i);
        }
        
        System.out.println("弹出");
        while(!s.isEmpty()){
          int j = s.pop();
          System.out.println(j);
        }
        
    }

  

输入
1
2
3
foreach
1
2
3
Iterator
1
2
3
弹出
3
2
1

posted @ 2022-11-06 08:30  yanher  阅读(91)  评论(0)    收藏  举报