從 Java 的棧中獲取一個元素但不移除它
方法 java.util.Stack.peek() 可用於從 Java 棧中獲取元素,而不將其移除。此方法不需要引數,它返回棧頂元素。如果棧為空,則丟擲 EmptyStackException。
演示此方法的程式如下 -
示例
import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Amy"); stack.push("John"); stack.push("Mary"); stack.push("Peter"); stack.push("Susan"); System.out.println("The stack elements are: " + stack); System.out.println("The element at the top of the stack is: " + stack.peek()); } }
輸出
The stack elements are: [Amy, John, Mary, Peter, Susan] The element at the top of the stack is: Susan
現在我們瞭解一下上面的程式。
先建立 Stack。然後使用 Stack.push() 方法向棧中新增元素。顯示棧,然後使用 Stack.peek() 方法返回棧頂元素並列印它。演示此方法的程式碼片段如下 -
Stack stack = new Stack(); stack.push("Amy"); stack.push("John"); stack.push("Mary"); stack.push("Peter"); stack.push("Susan"); System.out.println("The stack elements are: " + stack); System.out.println("The element at the top of the stack is: " + stack.peek());
廣告