Java Stack lastElement()方法与实例

Java Stack lastElement()方法与实例

Java.util.Stack.lastElement()方法是用来检索或获取Stack的最后一个元素。它返回存在于堆栈最后一个索引的元素。

语法

Stack.lastElement()

参数: 该方法不接受任何参数。

返回值: 该方法返回Stack中存在的 最后一个元素

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

程序1 :

// Java code to illustrate lastElement()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<String> stack = new Stack<String>();
  
        // 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 last element
        System.out.println("The last element is: "
                           + stack.lastElement());
    }
}

输出:

Stack: [Welcome, To, Geeks, 4, Geeks]
The last element is: Geeks

示例2

// Java code to illustrate lastElement()
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<Integer> stack = new Stack<Integer>();
  
        // 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 last element
        System.out.println("The last element is: "
                           + stack.lastElement());
    }
}

输出:

Stack: [10, 15, 30, 20, 5]
The last element is: 5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程