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


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


Java中的Java.util.Stack.firstElement()方法用於檢索或獲取Stack的第一個元素。它返回存在於0處的元素th堆棧索引

用法:

Stack.firstElement()

參數:該方法不帶任何參數。


返回值:該方法返回堆棧中存在的第一個元素。

以下示例程序旨在說明Java.util.Stack.firstElement()方法:

程序1:

// Java code to illustrate firstElement() 
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 into the Stack 
        stack.add("Welcome"); 
        stack.add("To"); 
        stack.add("Geeks"); 
        stack.add("4"); 
        stack.add("Geeks"); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Displaying the first element 
        System.out.println("The first element is: "
                           + stack.firstElement()); 
    } 
}
輸出:
Stack: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome

程序2:

// Java code to illustrate firstElement() 
import java.util.*; 
  
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 into the Stack 
        stack.add(10); 
        stack.add(15); 
        stack.add(30); 
        stack.add(20); 
        stack.add(5); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Displaying the first element 
        System.out.println("The first element is: "
                           + stack.firstElement()); 
    } 
}
輸出:
Stack: [10, 15, 30, 20, 5]
The first element is: 10


相關用法


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