What is the Stack.elements method in Java?

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

What is the elements() method in Stack?

The elements() method can be used to get all the values of the Stack object as an Enumeration object.

Syntax

public Enumeration<V> elements()

Parameters

This method doesn’t take any arguments.

Return value

The elements() method will return an Enumeration for the values of the Stack. In the returned Enumeration, the items are generated based on the index. For example, the first item generated will be the element at index 0.

Code

The example below shows how to use the elements() method.

import java.util.Stack;
import java.util.Enumeration;
class ElementsExample {
public static void main( String args[] ) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("The Stack is :" + stack);
Enumeration<Integer> elements = stack.elements();
System.out.print("The values are : ");
while(elements.hasMoreElements()) {
System.out.print(elements.nextElement() + ",");
}
}
}

Explanation

In the code above:

  • In lines 1 and 2, we imported the Stack and Enumeration classes.

  • In line 6, we created a new object for the Stack class with the name stack.

  • In lines 7, 8, and 9, we use the push method to add three elements, 1,2,3, into the stack object.

  • In line 12, we get the values present in the stack using the elements() method and store them in the elements variable. Then, we print the elements object by using the while loop, hasMoreElements, and nextElement methods.

Free Resources