當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。