Java.util.Stack 类

java.util.Stack.get() 方法返回堆栈指定索引处的元素。

语法

public E get(int index)

这里,E是容器维护的元素类型。

参数

index 指定栈中元素的索引号。

返回值

返回值堆栈指定索引处的元素。

异常

如果索引超出范围,则抛出 IndexOutOfBoundsException

示例:

在下面的示例中,java.util.Stack.get() 方法返回堆栈指定索引处的元素。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建堆栈
    Stack<Integer> MyStack = new Stack<Integer>();

    //填充堆栈
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);
    MyStack.push(50);

    //使用get()方法打印堆栈
    System.out.print("MyStack contains:"); 
    for(int i = 0; i < MyStack.size(); i++) {
      System.out.print(" " + MyStack.get(i));
    }
  }
}

上述代码的输出将是:

MyStack contains: 10 20 30 40 50