方法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.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());