Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

stack
elements
java
communitycreator

What is the Stack.elements method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

stack
elements
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring