在Java中使用示例的Stack get()方法
Java.util.Stack.get()方法用于从Stack中获取或检索特定索引处的元素。
语法(语法):
Stack.get(int index)
参数(参数): 该方法接受一个必填参数 index(索引) ,它是整型数据类型。它指定了要从Stack获取的元素的位置或索引。
Return Value(返回值): 该方法返回指定参数索引所在位置的 element(元素) 。
下面的程序说明了Java.util.Stack.get()方法:
Program 1: :
// Java code to illustrate get() method
import java.util.*;
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.get(2));
}
}
Stack: [Geeks, for, Geeks, 10, 20]
The element is: Geeks
Program 2: :
// Java code to illustrate get() 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("1");
stack.add("2");
stack.add("3");
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.get(4));
}
}
Stack: [1, 2, 3, 10, 20]
The element is: 20