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


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


Java中的java.util.Stack.peek()方法用於檢索或獲取Stack的第一個元素或位於Stack頂部的元素。檢索到的元素不會被刪除或從堆棧中刪除。

用法:

STACK.peek()

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


返回值:該方法返回堆棧頂部的元素,如果堆棧為空,則返回NULL。

異常:如果堆棧為空,則該方法引發EmptyStackException。

以下程序說明了java.util.Stack.peek()方法:
示例1:

// Java code to illustrate peek() function 
  
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<String> STACK = new Stack<String>(); 
  
        // Use push() to add elements into the Stack 
        STACK.push("Welcome"); 
        STACK.push("To"); 
        STACK.push("Geeks"); 
        STACK.push("For"); 
        STACK.push("Geeks"); 
  
        // Displaying the Stack 
        System.out.println("Initial Stack: " + STACK); 
  
        // Fetching the element at the head of the Stack 
        System.out.println("The element at the top of the"
                           + " stack is: " + STACK.peek()); 
  
        // Displaying the Stack after the Operation 
        System.out.println("Final Stack: " + STACK); 
    } 
}
輸出:
Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]

示例2:

// Java code to illustrate peek() function 
  
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<Integer> STACK = new Stack<Integer>(); 
  
        // Use push() to add elements into the Stack 
        STACK.push(10); 
        STACK.push(15); 
        STACK.push(30); 
        STACK.push(20); 
        STACK.push(5); 
  
        // Displaying the Stack 
        System.out.println("Initial Stack: " + STACK); 
  
        // Fetching the element at the head of the Stack 
        System.out.println("The element at the top of the"
                           + " stack is: " + STACK.peek()); 
  
        // Displaying the Stack after the Operation 
        System.out.println("Final Stack: " + STACK); 
    } 
}
輸出:
Initial Stack: [10, 15, 30, 20, 5]
The element at the top of the stack is: 5
Final Stack: [10, 15, 30, 20, 5]


相關用法


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