Java Stack get()方法与实例

Java Stack get()方法与实例

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

语法

Stack.get(int index)

参数: 该方法接受一个强制性参数index,它是整数数据类型。它指定了要从堆栈中获取的元素的位置或索引。

返回值: 该方法返回参数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<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

程序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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程