當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack elementAt()用法及代碼示例


Java.util.Stack.elementAt(int pos)方法用於從堆棧中的特定索引處獲取或檢索元素。

用法:

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


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack elementAt() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。