Java Stack elementAt()方法与实例
Java.util.Stack.elementAt( int pos )方法用于从Stack的特定索引中获取或检索一个元素。
语法
Stack.elementAt(int pos)
参数: 该方法接受一个强制性的整数数据类型的参数pos,指定要从堆栈中获取的元素的位置或索引。
返回值: 该方法返回由参数pos指定的位置上的元素。
下面的程序说明了Java.util.Stack.get()方法。
程序1 :
// Java code to illustrate elementAt() method
import java.util.Stack;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Displaying the Stack
System.out.println("Stack: "
+ stack);
// Fetching the specific element from the Stack
System.out.println("The element is: "
+ stack.elementAt(3));
}
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
The element is: 10
示例2
// Java code to illustrate elementAt() method
import java.util.Stack;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack = new Stack<Integer>();
// Use add() method to add elements in the Stack
stack.add(1);
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
// Displaying the Stack
System.out.println("Stack: " + stack);
// Fetching the specific element from the Stack
System.out.println("The element is: "
+ stack.elementAt(1));
}
}
输出:
Stack: [1, 2, 3, 4, 5]
The element is: 2
极客教程