Java中Stack的elements()方法及示例

Java中Stack的elements()方法及示例

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

语法:

Enumeration enu = Stack.elements()

参数: 该方法不使用任何参数。

返回值: 该方法返回 枚举类型 的Stack值。

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

程序1:

// Java代码示例:illustrate the elements() method
import java.util.*;
  
public class Stack_Demo {
    public static void main(String[] args)
    {
  
        // 创建一个空Stack
        Stack<String> stack = new Stack<String>();
  
        // 向表中插入元素
        stack.add("Geeks");
        stack.add("4");
        stack.add("Geeks");
        stack.add("Welcomes");
        stack.add("You");
  
        // 显示Stack
        System.out.println("The Stack is: " + stack);
  
        // 创建一个空枚举来存储
        Enumeration enu = stack.elements();
  
        System.out.println("The enumeration of values are:");
  
        // 显示枚举
        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)
    {
  
        // 创建一个空Stack
        Stack<Integer> stack = new Stack<Integer>();
  
        // 向表中插入元素
        stack.add(10);
        stack.add(15);
        stack.add(20);
        stack.add(25);
        stack.add(30);
  
        // 显示Stack
        System.out.println("The Stack is: " + stack);
  
        // 创建一个空枚举来存储
        Enumeration enu = stack.elements();
  
        System.out.println("The enumeration of values are:");
  
        // 显示枚举
        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教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程