从 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());
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP