📜  Java中的堆栈get()方法与示例

📅  最后修改于: 2022-05-13 01:55:02.579000             🧑  作者: Mango

Java中的堆栈get()方法与示例

Java.util.Stack.get()方法用于从堆栈中获取或检索特定索引处的元素。

句法:

Stack.get(int index)

参数:此方法接受整数数据类型的强制参数索引。它指定要从堆栈中获取的元素的位置或索引。

返回值:该方法返回存在于参数索引指定位置的元素

下面的程序说明了Java.util.Stack.get() 方法:

程序 1

// Java code to illustrate get() method
import java.util.*;
  
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.get(2));
    }
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
The element is: Geeks

方案二

// Java code to illustrate get() 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("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