📜  在Java中使用示例堆栈 firstElement() 方法

📅  最后修改于: 2022-05-13 01:55:02.417000             🧑  作者: Mango

在Java中使用示例堆栈 firstElement() 方法

Java 中的Java Java ()方法用于检索或获取堆栈的第一个元素。它返回存在于 Stack 的第 0索引处的元素

句法:

Stack.firstElement()

参数:该方法不带任何参数。

返回值:该方法返回堆栈中存在的第一个元素

下面的程序说明了Java.util.Stack.firstElement() 方法:

方案一:

// Java code to illustrate firstElement()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // Use add() method to add elements into the Stack
        stack.add("Welcome");
        stack.add("To");
        stack.add("Geeks");
        stack.add("4");
        stack.add("Geeks");
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // Displaying the first element
        System.out.println("The first element is: "
                           + stack.firstElement());
    }
}
输出:
Stack: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome

方案二:

// Java code to illustrate firstElement()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack stack = new Stack();
  
        // Use add() method to add elements into the Stack
        stack.add(10);
        stack.add(15);
        stack.add(30);
        stack.add(20);
        stack.add(5);
  
        // Displaying the Stack
        System.out.println("Stack: " + stack);
  
        // Displaying the first element
        System.out.println("The first element is: "
                           + stack.firstElement());
    }
}
输出:
Stack: [10, 15, 30, 20, 5]
The first element is: 10