HomeLanguagesJavaStack elements() method in Java with Example

Stack elements() method in Java with Example

The Java.util.Stack.elements() method of Stack class in Java is used to get the enumeration of the values present in the Stack.

Syntax:

Enumeration enu = Stack.elements()

Parameters: The method does not take any parameters.

Return value: The method returns an enumeration of the values of the Stack.

Below programs are used to illustrate the working of the java.util.Stack.elements() method:

Program 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());
        }
    }
}


Output:

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

Program 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());
        }
    }
}


Output:

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

1 COMMENT

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS