Stack peek() Method in Java

Java中的java.util.Stack.peek()方法用于检索或获取Stack的第一个元素或位于Stack顶部的元素。 检索到的元素不会被删除或从堆栈中删除。

Return Value: 该方法返回堆栈顶部的元素,如果堆栈为空,则返回NULL。

Exception: 如果堆栈为空,该方法将抛出EmptyStackException异常。

java.util.Stack.peek()方法举例:


import java.util.Stack;

public class stackep {

    public static void main(String[] args){

        Stack<Integer> STACK =new Stack<Integer>();

        STACK.push(10);

        STACK.push(15);

        STACK.push(30);

        STACK.push(20);

        STACK.push(5);

        System.out.println("Initial Stack:"+STACK);

        System.out.println("The Element at the top of the stack is "+STACK.peek());

        System.out.println("Final Stack:"+STACK);

    }

}

输出:

Initial Stack:[10, 15, 30, 20, 5]

The Element at the top of the stack is 5

Final Stack:[10, 15, 30, 20, 5]

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。