What is the Stack.elementAt method in Java?
The
Stackclass follows Last-In-First-Out (LIFO) principle. The element inserted first is processed last and the element inserted last is processed first. This class is present in thejava.utilpackage. This class extends theVectorclass and implements some methods specific to Stack methods, likepushandpop.
The above image shows how a stack will be. The new stone will be always kept at the top and the stone which is last kept will be taken first. The image is taken from here.
The elementAt method of the Stack class can be used to get the element at a specific index of the Stack object.
Syntax
public E elementAt(int index)
Parameters
This method’s argument is the index from which the element is to be fetched. The index should be positive and less than the size of the Stack object. Otherwise, an ArrayIndexOutOfBoundsException will be thrown.
index>= 0 &&index< size()`
Return value
This method returns the element present at the passed index.
Code
import java.util.Stack;class RemoveAll {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// add elememtsstack.push(1);stack.push(2);stack.push(3);System.out.println("The stack is: " + stack);System.out.println("Element at index 0 : " + stack.elementAt(0));System.out.println("Element at index 1 : " + stack.elementAt(1));System.out.println("Element at index 2 : " + stack.elementAt(2));}}
Please click the “Run” button on the code section above to see how the
elementAtmethod works.
Explanation
In the code above,
-
Line 5: We create an object for the
Stackclass with the namestack. -
Lines 8 to 10: We add three elements (
1,2,3) to the createdstackobject using thepushmethod. -
Lines 14 to 16: We used the
elementAtmethod of thestackobject to get the element present at the indices0,1, and2.