Java中的 Stack elementAt() 方法与示例
Java.util.Stack.elementAt( int pos )方法用于从堆栈中获取或检索特定索引处的元素。
句法:
Stack.elementAt(int pos)
参数:此方法接受整数数据类型的强制参数pos ,该参数指定要从堆栈中获取的元素的位置或索引。
返回值:该方法返回存在于参数pos指定位置的元素。
下面的程序说明了Java.util.Stack.get() 方法:
方案一:
// Java code to illustrate elementAt() method
import java.util.Stack;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// 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
方案二:
// Java code to illustrate elementAt() method
import java.util.Stack;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// 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