Java Stack elements()方法及实例

Java Stack elements()方法及实例

Java中Stack类的Java.util.Stack.elements()方法是用来获取Stack中存在的枚举值的。

语法

Enumeration enu = Stack.elements()

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

返回值: 该方法返回一个堆栈的 枚举 值。

下面的程序用来说明java.util.Stack.elements()方法的工作。

程序1 :

// Java code to illustrate the elements() method
import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Stack
        Stack<String> stack = new Stack<String>();
  
        // Inserting elements into the table
        stack.add("Geeks");
        stack.add("4");
        stack.add("Geeks");
        stack.add("Welcomes");
        stack.add("You");
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack);
  
        // Creating an empty enumeration to store
        Enumeration enu = stack.elements();
  
        System.out.println("The enumeration of values are:");
  
        // Displaying the Enumeration
        while (enu.hasMoreElements()) {
            System.out.println(enu.nextElement());
        }
    }
}

输出:

The Stack is: [Geeks, 4, Geeks, Welcomes, You]
The enumeration of values are:
Geeks
4
Geeks
Welcomes
You

程序2 :

import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Stack
        Stack<Integer> stack = new Stack<Integer>();
  
        // Inserting elements into the table
        stack.add(10);
        stack.add(15);
        stack.add(20);
        stack.add(25);
        stack.add(30);
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack);
  
        // Creating an empty enumeration to store
        Enumeration enu = stack.elements();
  
        System.out.println("The enumeration of values are:");
  
        // Displaying the Enumeration
        while (enu.hasMoreElements()) {
            System.out.println(enu.nextElement());
        }
    }
}

输出:

The Stack is: [10, 15, 20, 25, 30]
The enumeration of values are:
10
15
20
25
30

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程