从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 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短