从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.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());热门推荐
10 送离职同事简短祝福语
11 员工对同事祝福语简短
12 写给兄弟的祝福语简短
13 生日祝福语简短独特格式
14 新年发给客户祝福语简短
15 圣诞简短祝福语给父母
16 讲课祝福语简短10字
17 新老师祝福语 简短独特
18 對好友毕业祝福语简短