当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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


相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack elements() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。