What is the Stack.elements method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
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
StackandEnumerationclasses. -
In line 6, we created a new object for the
Stackclass with the namestack. -
In lines 7, 8, and 9, we use the
pushmethod to add three elements,1,2,3, into thestackobject. -
In line 12, we get the values present in the
stackusing theelements()method and store them in theelementsvariable. Then, we print theelementsobject by using thewhileloop, hasMoreElements, and nextElement methods.